如何获取存储在字节数组中的字节的二进制值 [英] how to get the binary values of the bytes stored in byte array
本文介绍了如何获取存储在字节数组中的字节的二进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个项目,该项目将文件中的数据转换为字节数组,并将0添加到该字节数组,直到字节数组的长度为224位。我能够添加零,但我无法确认多少零是足够的。所以我想以二进制格式打印字节数组中的文件数据。任何人都可以帮助我吗?
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?
推荐答案
对于每个字节:
- 强制转换为
int
(通过自动扩展byte
到<$ c,在下一步中发生$ c> int ) - 按位-AND,掩码255为零除了最后8位
- 按位 - 或者使用256将第9位设置为1,使所有值正好为9位长
- 调用
Integer.toBinaryString()
生成9位字符串 - 调用
字符串#substring(1)
删除前导1,只留下8个二进制字符(带前导)零(如果有的话,原封不动))
- cast to
int
(happens in the next step via automatic widening ofbyte
toint
) - 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)
代码是:
byte[] bytes = "\377\0\317\tabc".getBytes();
for (byte b : bytes) {
System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}
上述代码的输出(总是8位宽):
Output of above code (always 8-bits wide):
11111111
00000000
11001111
00001001
01100001
01100010
01100011
这篇关于如何获取存储在字节数组中的字节的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文