[英]How to convert A string that represents an integer to unsigned byte array in Java?
Basically, what I want is to convert a string like "123456"
to unsigned byte array: [1, 226, 64]
. 基本上,我想要的是将像"123456"
这样的字符串转换为无符号字节数组: [1, 226, 64]
。 However, I look everywhere and what I found is to get the 2's complements (signed) byte array [1, -30, 64]
: 但是,我到处寻找,我发现的是得到2的补码(带符号)字节数组[1, -30, 64]
:
byte[] array = new BigInteger("123456").toByteArray();
System.out.println(Arrays.toString(array));
OUTPUT: OUTPUT:
[1, -30, 64]
So, how can it be done in Java? 那么,如何在Java中完成呢? I want the output to be: 我希望输出为:
[1, 226, 64]
EDIT: I know that byte can hold only up to 127, so instead of byte array I need it to be int array. 编辑:我知道该字节最多只能容纳127个字节,因此我需要将它作为int数组而不是字节数组。
Java has no unsigned types, so you'll have to store the values in an int array. Java没有无符号类型,因此您必须将值存储在int数组中。
byte[] array = new BigInteger("123456").toByteArray();
int[] unsigned_array = new int[array.length];
for (int i = 0; i < array.length; i++) {
unsigned_array[i] = array[i] >= 0 ? array[i] : array[i] + 256;
}
Fairly straightforward. 非常坦率的。
Java does not have unsigned bytes, so to convert them to ints as if they were unsigned, you need to AND them bitwise ( &
) with int 0xFF
: Java没有无符号字节,因此要将它们转换为整数,就好像它们是无符号的一样,你需要按顺序( &
)与int 0xFF
对它们进行AND运算:
byte[] array = new BigInteger("123456").toByteArray();
for (int i = 0; i < array.length; i++) {
System.out.println(0xFF & array[i]);
}
Output: 输出:
1
226
64
You don't necessarily need to store them as an int array - it depends what you want to do with them... 你不一定需要将它们存储为一个int数组 - 这取决于你想用它们做什么......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.