将字节(java数据类型)值转换为位(仅包含8位的字符串) [英] Convert byte (java data type) value to bits (a string containing only 8 bits)

查看:271
本文介绍了将字节(java数据类型)值转换为位(仅包含8位的字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.)

在你认为这已被多次回答之前,请让我解释为什么我感到困惑。

byte这个名字有点含糊不清。所以,跟随其他答案很难。对于我的问题, byte 指的是占用8位的 java数据类型,其值范围为-128到127.我也不喜欢意思是字节数组。我的问题是关于仅将单个值转换为其8位表示。没有更多。

The name "byte" is a little ambiguous. So, it's been difficult following other answers. For my question, byte is referring to the java data type that 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 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)?

推荐答案

尝试

Integer.toBinaryString(b & 0xFF); 

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

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)

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

这篇关于将字节(java数据类型)值转换为位(仅包含8位的字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆