Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a stream of bits in java

Tags:

java

string

How to convert a string to a stream of bits zeroes and ones what i did i take a string then convert it to an array of char then i used method called forDigit(char,int) ,but it does not give me the character as a stream of 0 and 1 could you help please. also how could i do the reverse from bit to a char. pleaes show me a sample

like image 464
Bob2 Avatar asked Dec 11 '10 13:12

Bob2


1 Answers

Its easiest if you take two steps. String supports converting from String to/from byte[] and BigInteger can convert byte[] into binary text and back.

String text = "Hello World!";
System.out.println("Text: "+text);

String binary = new BigInteger(text.getBytes()).toString(2);
System.out.println("As binary: "+binary);

String text2 = new String(new BigInteger(binary, 2).toByteArray());
System.out.println("As text: "+text2);

Prints

Text: Hello World!
As binary: 10010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001
As text: Hello World!
like image 157
Peter Lawrey Avatar answered Sep 19 '22 04:09

Peter Lawrey