将字节(java 数据类型)值转换为位(仅包含 8 位的字符串)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14364054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:01:12  来源:igfitidea点击:

Convert byte (java data type) value to bits (a string containing only 8 bits)

javabyte

提问by davidXYZ

I need to convert a value declared as a byte data type into a string of 8 bits. Is there any Java library method that can do this? For example, it should take in -128 and output "10000000". Also, input -3 should give "11111101". (I converted these by hand.)

我需要将声明为字节数据类型的值转换为 8 位字符串。有没有可以做到这一点的Java库方法?例如,它应该输入 -128 并输出“10000000”。此外,输入 -3 应给出“11111101”。(我手工转换了这些。)

Before you assume this has been answered many times, please let me explain why I am confused.

在您认为这个问题已被多次回答之前,请让我解释一下我为什么感到困惑。

The name "byte" is a little ambiguous. So, it's been difficult following other answers. For my question, byteis referring to the java data typethat takes up 8 bits and whose value ranges from -128 to 127. I also don't mean an "array of bytes". My question is about converting a single value into its 8-bit representation only. Nothing more.

“字节”这个名字有点含糊。因此,很难遵循其他答案。对于我的问题,byte是指占用 8 位且其值范围从 -128 到 127的java 数据类型。我也不是指“字节数组”。我的问题是关于仅将单个值转换为其 8 位表示。而已。

I've tried these:

我试过这些:

byte b = -128;  //i want 10000000
Integer.toBinaryString(b); //prints 11111111111111111111111110000000
Integer.toString(b, 2); //prints -10000000

If there's no built-in method, can you suggest any approach (maybe bit shifting)?

如果没有内置方法,您能否提出任何方法(可能是位移)?

回答by Evgeniy Dorofeev

Try

尝试

Integer.toBinaryString(b & 0xFF); 

this gives a floating length format e.g. 4-> 100. There seems to be no standard solution to get a fixed length format, that is 4-> 00000100. Here is a one line custom solution (prepended with 0b)

这给出了一个浮动长度格式,例如4-> 100。似乎没有获得固定长度格式的标准解决方案,即4-> 00000100。这是一个单行自定义解决方案(以 开头0b

String s ="0b" + ("0000000" + Integer.toBinaryString(0xFF & b)).replaceAll(".*(.{8})$", "");