[英]How to convert an array of bits to a single char in java?
I am working with an array of 8 bits and I am trying to convert it to a single char in Java. 我正在使用8位数组,正在尝试将其转换为Java中的单个char。 I am trying to do something along the lines of 我正在尝试做一些类似的事情
byte[] bytes2 = {0,0,0,0,0,0,0,0};
char c = (char) bytes2);
It is throwing a compilation error that I can not case a byte[] to a char. 它引发了编译错误,我无法将byte []设置为char。 I have gotten it to compile, but not work correctly by assigning char c to just one of the elements of the array. 我已经将其编译,但仅通过将char c分配给数组的元素之一才能正常工作。 I am just stuck on this part, and would appreciate a little bit of help. 我只是停留在这一部分,并希望获得一些帮助。
Thank you 谢谢
byte[]
is array of bytes, and 1 byte is 8 bit, 1 char is also 8 bit. byte[]
是字节数组,1个字节是8位,1个char也是8位。
You initiate byte[]
with {0,0,0,0,0,0,0,0}
; 您用{0,0,0,0,0,0,0,0}
初始化byte[]
; It means your store 8 * 8 = 64 bits in bytes2
variable. 这意味着您的存储8 * 8 = 64位(以bytes2
。
So you can't store 64 bits data into single char (8 bit). 因此,您不能将64位数据存储到单个字符(8位)中。
But you can do this: 但是您可以这样做:
byte[] bytes2 = {0,0,0,0,0,0,0,0};
char c = (char) bytes2[0]; // store first element (8 bit) into single char (1 bit) and cast it.
You can't convert it to a one single char
. 您不能将其转换为一个char
。 Instead of that you can convert it to a single String
and then convert that to a char
array like below, 除此之外,您可以将其转换为单个String
,然后将其转换为如下所示的char
数组,
byte[] bits2 = {0, 0, 0, 0, 0, 0, 0, 0};
String value = new String(bits2);
char[] chars = value.toCharArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.