How to get binary values โ€‹โ€‹of bytes stored in a byte array

I am working on a project that receives data from a file in a byte array and adds โ€œ0โ€ to this byte array until the length of the byte array is 224 bits. I was able to add zero, but I cannot confirm how many zeros are enough. So I want to print the file data in an array of bytes in binary format. Can anybody help me?

+6
source share
3 answers

For each byte:

  • discarded by int (happens in the next step by automatically extending byte to int )
  • bitwise-And with a mask of 255 to zero everything except the last 8 bits
  • bitwise OR from 256 to set the 9th bit to one, making all values โ€‹โ€‹exactly 9 bits long
  • invoke Integer.toBinaryString() to create a 9-bit string
  • invoke String#substring(1) to "remove the" leading "1", leaving exactly 8 binary characters (with leading zeros, if any, untouched)

What code is:

 byte[] bytes = "\377\0\317\tabc".getBytes(); for (byte b : bytes) { System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); } 

The output above the code (always 8 bits):

 11111111 00000000 11001111 00001001 01100001 01100010 01100011 
+19
source

Try Integer.toString (bytevalue, 2)

Ok, where toBinaryString ? It is also possible to use this.

+1
source

Initialize the byte array first with 0s:

 byte[] b = new byte[224]; Arrays.fill(b, 0); 

Now just fill the array with your data. Any remaining bytes will be 0.

-2
source

Source: https://habr.com/ru/post/890807/


All Articles