Convert String binary to bit in java

I had a question about converting a binary number of type String to bit and writing to a txt file.

For example, we have String as "0101011" and you want to convert to bit type "0101011" then write to a file on disk.

I would like to know if there is anyway to hide the string in bit.

I searched on the Internet, they suggest using bitarray, but I'm not sure

thanks

+4
source share
3 answers

Try the following:

int value = Integer.parseInt("0101011", 2); // parse base 2 

Then the bitmap in value will correspond to the binary interpretation of the string "0101011" . Then you can write the value to the file as byte (provided that the string contains no more than 8 binary digits).

EDIT You can also use Byte.parseByte("0101011", 2); . However, byte values ​​in Java are always signed. If you tried to parse an 8-bit value with the 8 th bit set (for example, "10010110" , which is 150 decimal), you will get a NumberFormatException because the values ​​above +127 are not suitable in byte . If you don't need to process bit patterns more than "01111111" , then Byte.parseByte works just as well as Integer.parseInt .

Recall, however, that to write a byte to a file, you use OutputStream.write(int) , which takes the value int (not byte ) - although it only writes one byte. You can also go with an int value to start with.

+4
source

You can try the code below to avoid overflowing numbers.

  long avoidOverflows = Long.parseLong("11000000000000000000000000000000", 2); int thisShouldBeANegativeNumber = (int) avoidOverflows; System.out.println("Currect value : " + avoidOverflows + " -> " + "Int value : " + thisShouldBeANegativeNumber); 

you can see the result

 Currect value : 3221225472 -> Int value : -1073741824 
0
source
 //Converting String to Bytes bytes[] cipherText= new String("0101011").getBytes() //Converting bytes to Bits and Convert to String StringBuilder sb = new StringBuilder(cipherText.length * Byte.SIZE); for( int i = 0; i < Byte.SIZE * cipherText .length; i++ ) sb.append((cipherText [i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1'); //Byte code of input in Stirn form System.out.println("Bytecode="+sb.toString()); // some binary data //Convert Byte To characters String bin = sb.toString(); StringBuilder b = new StringBuilder(); int len = bin.length(); int i = 0; while (i + 8 <= len) { char c = convert(bin.substring(i, i+8)); i+=8; b.append(c); } //String format of Binary data System.out.println(b.toString()); 
0
source

All Articles