convert binary to text java - CompareEssaydatesCom

convert binary to text java












  • FAQs

  • Search

  • Recent Topics

  • Flagged Topics

  • Hot Topics

  • Best Topics

  • Register / Login

Logo

    • Post Reply
      Bookmark Topic
      Watch Topic

    • New Topic
    programming forums
    Java
    Mobile
    Certification
    Databases
    Caching
    Books
    Engineering
    Micro Controllers
    OS
    Languages
    Paradigms
    IDEs
    Build Tools
    Frameworks
    Application Servers
    Open Source
    This Site
    Careers
    Other
    all forums

    this forum made possible by our volunteer staff, including …
    Marshals:
    • Campbell Ritchie
    • Bear Bibeault
    • Jeanne Boyarsky
    • Liutauras Vilda
    • Tim Cooke
    Sheriffs:
    • Henry Wong
    • Devaka Cooray
    • Junilu Lacar
    Saloon Keepers:
    • Ron McLeod
    • Pete Letkeman
    • Tim Moores
    • Stephan van Hulst
    • Carey Brown
    Bartenders:
    • Tim Holloway
    • Frits Walraven
    • salvin francis

    • Beginning Java


    Java: Convert a binary file to "text" and back again.
      RSS feed

     
    Mads Nielsen
    Greenhorn
    Posts: 28


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Hello

    I am fooling aroung with Java , wondering how to read a binary file and convert it to text and then back again to binary.

    This is what i have so far:

    The above code does not work on binary data.

    Kind regards Mads Nielsen

     
    Jesper de Jong
    Java Cowboy

    Sheriff
    Posts: 16084
    88
    I like…
    Android
    IntelliJ IDE
    Java
    Scala
    Spring


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Java has two kinds of classes for I/O:

  • Streams (InputStreams and OutputStreams) are for reading and writing binary data.
  • Readers and Writers are for reading files that can be interpreted as characters (text) using a character encoding.
  • Trying to read and write files that contain data that is not meant to be interpreted as text, such as *.zip and *.exe files, will lead to problems. You might get an exception while reading the file, for example if the character encoding that converts the bytes to characters encounters a sequence of bytes that cannot be properly interpreted as text. You might also get a corrupted output file, because the conversion from bytes to characters and back to bytes is not always 100% reversible (for complicated reasons).

    If you just want to copy files, then use InputStreams and OutputStreams to do so (that will also work for text files). You can find examples easily by searching.

    Jesper’s Blog – Pluralsight Author Page

     
    Mads Nielsen
    Greenhorn
    Posts: 28


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Jesper de Jong wrote:Java has two kinds of classes for I/O:

  • Streams (InputStreams and OutputStreams) are for reading and writing binary data.
  • Readers and Writers are for reading files that can be interpreted as characters (text) using a character encoding.
  • Trying to read and write files that contain data that is not meant to be interpreted as text, such as *.zip and *.exe files, will lead to problems. You might get an exception while reading the file, for example if the character encoding that converts the bytes to characters encounters a sequence of bytes that cannot be properly interpreted as text. You might also get a corrupted output file, because the conversion from bytes to characters and back to bytes is not always 100% reversible (for complicated reasons).

    If you just want to copy files, then use InputStreams and OutputStreams to do so (that will also work for text files). You can find examples easily by searching.

    The problem is that i need to send the file over a socket later, so i need the file data in a format i can send.

     
    Paul Clapham
    Sheriff
    Posts: 23598
    48
    I like…
    Eclipse IDE
    Firefox Browser
    MySQL Database


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Mads Nielsen wrote:The problem is that i need to send the file over a socket later, so i need the file data in a format i can send.

    Okay… but what you send over the socket is bytes. So this requirement of converting binary data to “text” seems to be irrelevant. Where did it come from?

     
    Mads Nielsen
    Greenhorn
    Posts: 28


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Paul Clapham wrote:

    Mads Nielsen wrote:The problem is that i need to send the file over a socket later, so i need the file data in a format i can send.

    Okay… but what you send over the socket is bytes. So this requirement of converting binary data to “text” seems to be irrelevant. Where did it come from?

    Well, not litteraly text, i just mean i need the file data in a format i can feed to the socket. Bytes will do just fine.

     
    Jesper de Jong
    Java Cowboy

    Sheriff
    Posts: 16084
    88
    I like…
    Android
    IntelliJ IDE
    Java
    Scala
    Spring


    posted 6 years ago


    • Likes 1

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Class Socket has getInputStream and getOutputStream methods. You can use the InputStream and OutputStream that those methods return just like any other InputStream or OutputStream. Data does not necessarily need to be text to be sent over a socket connection.

    Jesper’s Blog – Pluralsight Author Page

     
    Mads Nielsen
    Greenhorn
    Posts: 28


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    Jesper de Jong wrote:Class Socket has getInputStream and getOutputStream methods. You can use the InputStream and OutputStream that those methods return just like any other InputStream or OutputStream. Data does not necessarily need to be text to be sent over a socket connection.

    Great, thanks.

     
    Mads Nielsen
    Greenhorn
    Posts: 28


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    I am reading files byte by byte now with DataInputStream.

    How do i create a file containing the bytes i have read from the original file ?

    Kind regards Mads Nielsen

     
    Paul Clapham
    Sheriff
    Posts: 23598
    48
    I like…
    Eclipse IDE
    Firefox Browser
    MySQL Database


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    You simply write the bytes to a FileOutputStream which refers to that file. Don’t forget to close the file after you finish.

    And by the way, there are two rules about when to use the “available” method of an InputStream:

    (1) Don’t use it unless you know what it does.

    (2) You don’t know what it does.

    Read our FAQ article Available Doesnt Do What You Think It Does for a more serious explanation.

     
    Jesper de Jong
    Java Cowboy

    Sheriff
    Posts: 16084
    88
    I like…
    Android
    IntelliJ IDE
    Java
    Scala
    Spring


    posted 6 years ago

    • Mark post as helpful



    • send pies

    • Quote

    • Report post to moderator

    What was the reason you chose to use DataInputStream?

    Why are you casting the bytes that you read from the file to char and print them to the console window (line 31)? This will lead to gibberish output on the console.

    You could read the content of the file into a byte array, like in this example. This example shows how to copy a file by reading blocks of data from a FileInputStream and writing those blocks to a FileOutputStream. It’s easy to change that example so that you write the bytes to an OutputStream that you get from a socket.

    Jesper’s Blog – Pluralsight Author Page

     
    You can’t expect to wield supreme executive power just because
    Why should you try IntelliJ IDEA ?

    https://coderanch.com/wiki/696337/IntelliJ-IDEA

    • Post Reply
      Bookmark Topic
      Watch Topic

    • New Topic
    Boost this thread!

    Similar Threads

    • Java I/O

    • How do I read and write a binary file?

    • Threads output

    • methods problem

    • Java Dynamic Servlet

    • More…

    Stack Overflow



    1. Log In
      Sign Up

    2. current community


      • Stack Overflow

        help
        chat

      • Meta Stack Overflow

      your communities

      Sign up or log in to customize your list.

      more stack exchange communities

      company blog

      • Tour

        Start here for a quick overview of the site

      • Help Center

        Detailed answers to any questions you might have

      • Meta

        Discuss the workings and policies of this site

      • About Us

        Learn more about Stack Overflow the company

      • Business

        Learn more about hiring developers or posting ads with us

    This site uses cookies to deliver our services and to show you relevant ads and job listings.
    By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .
    Your use of Stack Overflow’s Products and Services, including the Stack Overflow Network, is subject to these policies and terms.

    Join us in building a kind, collaborative learning community via our updated
    Code of Conduct .

    Join Stack Overflow to learn, share knowledge, and build your career.

    Email Sign Up
    Sign Up

    or sign in with


    Google

    Facebook

    Binary to text in Java

    Ask Question


    up vote
    6
    down vote

    favorite

    5

    I have a String with binary data in it (1110100) I want to get the text out so I can print it (1110100 would print “t”). I tried this, it is similar to what I used to transform my text to binary but it’s not working at all:

     public static String toText(String info)throws UnsupportedEncodingException byte[] encoded = info.getBytes(); String text = new String(encoded, "UTF-8"); System.out.println("print: "+text); return text; 

    Any corrections or suggestions would be much appreciated.

    Thanks!

    java string encoding utf-8 nsstringencoding
    share | improve this question

    edited Apr 26 ’13 at 13:09

    asked Nov 18 ’10 at 4:34

    Nick

    3053725

    add a comment  | 

    6 Answers
    6

    active

    oldest

    votes


    up vote
    26
    down vote

    accepted

    You can use Integer.parseInt with a radix of 2 (binary) to convert the binary string to an integer:

    int charCode = Integer.parseInt(info, 2);

    Then if you want the corresponding character as a string:

    String str = new Character((char)charCode).toString();

    share | improve this answer

    edited Nov 18 ’10 at 4:53

    answered Nov 18 ’10 at 4:40

    casablanca

    58.2k5105137

    • Thank you, it makes a lot of sense, but I don’t understand how to make a new Character from an int (charCode)
      –  Nick
      Nov 18 ’10 at 4:51

    • 2

      @Nick: Just cast it to char.
      –  casablanca
      Nov 18 ’10 at 4:54

    • great thank you very much!
      –  Nick
      Nov 18 ’10 at 4:57

    • can i name this thing as a vector representation of text ?
      –  S Gaber
      Apr 30 ’12 at 2:35

    add a comment  | 


    up vote
    4
    down vote

    I know the OP stated that their binary was in a String format but for the sake of completeness I thought I would add a solution to convert directly from a byte[] to an alphabetic String representation.

    As casablanca stated you basically need to obtain the numerical representation of the alphabetic character. If you are trying to convert anything longer than a single character it will probably come as a byte[] and instead of converting that to a string and then using a for loop to append the characters of each byte you can use ByteBuffer and CharBuffer to do the lifting for you:

    public static String bytesToAlphabeticString(byte[] bytes) CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer(); return cb.toString();

    N.B. Uses UTF char set

    Alternatively using the String constructor:

    String text = new String(bytes, 0, bytes.length, "ASCII");

    share | improve this answer

    edited Aug 13 ’14 at 12:38

    answered Aug 13 ’14 at 9:54

    tarka

    2,15453058

    add a comment  | 


    up vote
    2
    down vote

    This is my one (Working fine on Java 8):

    String input = "01110100"; // Binary input as String
    StringBuilder sb = new StringBuilder(); // Some place to store the chars
    Arrays.stream( // Create a Stream input.split("(?<=\\G.8)") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
    ).forEach(s -> // Go through each 8-char-section... sb.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
    );
    String output = sb.toString(); // Output text (t)

    and the compressed method printing to console:

    Arrays.stream(input.split("(?<=\\G.8)")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2)));
    System.out.print('\n');

    I am sure there are “better” ways to do this but this is the smallest one you can probably get.

    share | improve this answer

    answered Jun 19 ’16 at 13:24

    Leon Kasko

    377

    add a comment  | 


    up vote
    1
    down vote

    Here is the answer.

    private String[] splitByNumber(String s, int size) return s.split("(?<=\\G."+size+")");

    share | improve this answer

    edited Oct 2 ’12 at 9:42

    Marko

    13.7k103758

    answered Aug 14 ’12 at 17:39

    Nelson Poon

    111

    add a comment  | 


    up vote
    1
    down vote

    The other way around (Where “info” is the input text and “s” the binary version of it)

    byte[] bytes = info.getBytes();
    BigInteger bi = new BigInteger(bytes);
    String s = bi.toString(2); 

    share | improve this answer

    edited Jun 19 ’16 at 15:07

    Leon Kasko

    377

    answered Nov 18 ’10 at 4:51

    Emil

    8,115145398

    add a comment  | 


    up vote
    0
    down vote

    Look at the parseInt function. You may also need a cast and the Character.toString function.

    share | improve this answer

    answered Nov 18 ’10 at 4:37

    Matthew Flaschen

    212k36433493

    add a comment  | 

    Not the answer you’re looking for? Browse other questions tagged java string encoding utf-8 nsstringencoding or ask your own question .

    asked

    7 years, 9 months ago

    viewed

    57,095 times

    active

    2 years, 2 months ago

    Linked

    3

    How to convert binary to text in Java?

    -1

    Java Binary to Text Algorithm?

    2

    Convert binary string to ascii text?

    1

    Convert String / char into specified-digit binary string and vice versa in java

    1

    Binary string to text string Java Code

    0

    How to convert a binary value to ASCII in JAVA?

    3

    String of 0’s and 1’s to File as bits

    2

    Using binary data in android?

    1

    How can I convert ASCII to character in android?

    0

    Huffman compress file (Got the tree but can’t compress)- Java

    see more linked questions…

    Related

    5518

    Is Java “pass-by-reference” or “pass-by-value”?

    1920

    Does finally always execute in Java?

    2515

    In Java, difference between package private, public, protected, and private

    1836

    How do I call one constructor from another in Java?

    1221

    Fastest way to determine if an integer’s square root is an integer

    2912

    How do I generate random integers within a specific range in Java?

    1600

    Lookup Java enum by string value

    1282

    How to split a string in Java

    2531

    How do I convert a String to an int in Java?

    2651

    Creating a memory leak with Java

    Hot Network Questions

    • In a vacuum can a cooler body radiate Infrared radiation to a warmer body?

    • New developer can’t keep up with branch merges

    • Non-constant infinite arithmetic progressions?

    • How useful is an impregnable castle?

    • When someone’s ability to pay is suspect, why would it make sense to give them more expensive credit?

    • Rebus #19 is here

    • How would one attack or lay siege to a flying castle?

    • If you are falling, can you Misty Step to the ground to avoid damage?

    • Kid throwing ice cream cone back to the vendor

    • How to let users decide between transactions

    • Can you sneak into Premium Economy Class?

    • Are all fields in the universe we know of quantum fields?

    • Why were closed tape loops never a popular storage medium (or were they)?

    • Why is peer review so random?

    • Are there examples of conjectures supported by heuristic arguments that have been finally disproved?

    • Date of the Akeida?

    • An iron rain to starve a planet

    • Integers to English words in C

    • Geometric description of a certain sphere bundle

    • Can anyone tell me what this coin was used for, an approximate date and possibly what it’s worth?

    • I2C bus occupied

    • Why didn’t the Spacecraft used for the Apollo 11 mission melt in the Earth’s Atmosphere?

    • Get users to use the download button instead of right-click save

    • Why were floppy disks invented after hard disks?

    more hot questions


    question feed

    lang-java

    Stack Overflow works best with JavaScript enabled