Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

java - how to get the binary values of the bytes stored in byte array

i am working on a project that gets the data from the file into a byte array and adds "0" to that byte array until the length of the byte array is 224 bits. I was able to add zero's but i am unable to confirm that how many zero's are sufficient. So i want to print the file data in the byte array in binary format. Can anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For each byte:

  • cast to int (happens in the next step via automatic widening of byte to int)
  • bitwise-AND with mask 255 to zero all but the last 8 bits
  • bitwise-OR with 256 to set the 9th bit to one, making all values exactly 9 bits long
  • invoke Integer.toBinaryString() to produce a 9-bit String
  • invoke String#substring(1) to "delete" the leading "1", leaving exactly 8 binary characters (with leading zeroes, if any, intact)

Which as code is:

byte[] bytes = "377317abc".getBytes();
for (byte b : bytes) {
    System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}

Output of above code (always 8-bits wide):

11111111
00000000
11001111
00001001
01100001
01100010
01100011

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...