[英]turn negative bytes in byte array to positive by adding 256 - java
I have a byte array:我有一个字节数组:
byte[] b = [108, 108, -17, 65] // Arrays.toString(b)
and I want to turn negatives into negatives +256, like: -17 + 256 = 239 so that I have:我想把负数变成负数 +256,比如:-17 + 256 = 239 所以我有:
b = [108, 108, 239, 65]
I tried:我试过了:
ByteBuffer buffer = ByteBuffer.wrap(b);
for(int i = 0; i < 4; i++){
if (b[i] < 0){
int n = (b[i] + 256);
byte b1 = (byte) (b[i] + 256);
buffer.position(i);
buffer.put(i, (byte) (n & 0xFF));
}
}
but nothing changes.但没有任何变化。 I would be very thankful for any advices
我将非常感谢您的任何建议
You can't represent anything over 127 as a positive valued byte.您不能将超过 127 的任何内容表示为正值字节。 So you would have to have an array of
ints
to show
the value like you want.所以你必须有一个
ints
数组来show
你想要的值。 I use the word show
because it is important to realize that this is just a representation of the actual value for use by humans.我使用
show
这个词是因为重要的是要意识到这只是人类使用的实际价值的表示。 It has no bearing on the intrinsic nature of the value.它与价值的内在本质无关。
byte b = 239;
System.out.println(b);
Prints印刷
-17
I suspect you would want the unsigned value which can be printed like so.我怀疑你会想要可以像这样打印的无符号值。
byte b = -17;
System.out.println(Byte.toUnsignedInt(b));
Prints印刷
239
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.