-1

I need to convert a String value into Binary format. For Example: String str = "Java"; now i want to get it in binary format.how could i do this? any one could please help me!

Thanks in advane

user2451783
  • 71
  • 1
  • 2
  • 4
  • 3
    What is binary for you? What do you want to do with the value after? – Alexandre Lavoie Jun 12 '13 at 06:51
  • 1
    In what form do you want that binary representation? A ByteBuffe? A String of 1's and 0's? – Michael Lawrie Jun 12 '13 at 06:51
  • [Google](https://www.google.com.au/search?q=java%20string%20to%20binrary&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a&channel=np&source=hp#safe=off&client=firefox-a&hs=DNg&rls=org.mozilla:en-US:official&channel=np&q=java+string+to+binary&spell=1&sa=X&ei=dxq4UaD8HYaAiQf3-oHAAg&ved=0CCwQvwUoAA&bav=on.2,or.r_cp.r_qf.&bvm=bv.47810305,d.aGc&fp=57fbabeaac7c9348&biw=2560&bih=1470) – MadProgrammer Jun 12 '13 at 06:52
  • i wnat to get binary represenattion for the string "Java" in 1 byte. – user2451783 Jun 12 '13 at 07:17
  • @user2451783 give an example, this is vague. – Alexandre Lavoie Jun 12 '13 at 07:51

4 Answers4

2

Try this,

byte[] infoBin = null;
    infoBin = "Java".getBytes("UTF-8");
    for (byte b : infoBin) {
        System.out.println("c:" + (char) b + "-> "
                + Integer.toBinaryString(b));
    }

See this link : String to binary output in Java

Community
  • 1
  • 1
sais
  • 803
  • 6
  • 15
  • Thanks for your quick reply.But it is giving 40 bits binary value for the String "Java";But i want to get 8 bit binary value for this String "Java".How could i do? – user2451783 Jun 12 '13 at 07:13
1

Try this

  byte[] bytes = str.getBytes(charSetName);

this encodes str into a sequence of bytes using the named charset, storing the result into a byte array.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

string have getBytes() method.

  str.getBytes();
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

following will give you byte code;

 String str = "Java";
 byte[] bytecode=str.getBytes();
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115