[英]Byte array to signed Integer
I have the fallowing piece of code that I try to understand what it does.我有一段代码,我试图理解它的作用。 I know that extracts an integer value from a byte value, but I don't really comprehend what it does and how it works:我知道从字节值中提取 integer 值,但我并不真正理解它的作用和工作原理:
public int decodeInt(byte[] input, int length) {
int value = 0;
int p = 0;
int paddingPositions = 4 - length;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
if (paddingPositions-- > 0) {
value += (0 & 0x000000FF) << shift;
} else {
value += (input[p] & 0x000000FF) << shift;
p++
}
}
return value;
}
It seems to pad the value to get the high bits and low bits and sum them together somehow(the shift step looks very strange to me).它似乎填充值以获得高位和低位并以某种方式将它们相加(移位步骤对我来说看起来很奇怪)。
I would call this function keepFirstXBytes(...)
.我会称之为 function keepFirstXBytes(...)
。 It seems to cut out the first part of a byte[]
and return those bytes as an integer.它似乎删除了byte[]
的第一部分并将这些字节作为 integer 返回。
{ 0x01, 0x02, 0x03 }
, and your length is 2
, then it will output only the first 2 bytes.就像如果您的输入是: { 0x01, 0x02, 0x03 }
并且您的长度是2
,那么它将 output 只有前 2 个字节。 0x0102
. 0x0102
。There are some caveats.有一些注意事项。
length
is 4. If you take a longer value, then it will just act as if it was 4. It will just take the first 4 bytes of the array. length
的最大值是 4。如果你取一个更长的值,那么它就像是 4 一样。它将只取数组的前 4 个字节。 An integer can hold only 4 bytes after all.一个 integer 毕竟只能容纳 4 个字节。 I'm wondering if it could be easier to read, if it used an arraycopy
.我想知道如果它使用arraycopy
是否会更容易阅读。
byte[] destination = new byte[length];
System.arraycopy(input, 0, destination, 0, length);
And then finally convert that to an integer. Which is kind of tricky for an array of variable length.然后最终将其转换为 integer。这对于可变长度数组来说有点棘手。 So, I would borrow the function which I found here .所以,我会借用我在这里找到的 function。
public static int pareAsBigEndianByteArray(byte[] bytes) {
int factor = bytes.length - 1;
int result = 0;
for (int i = 0; i < bytes.length; i++) {
if (i == 0) {
result |= bytes[i] << (8 * factor--);
} else {
result |= bytes[i] << (8 * factor--);
}
}
return result;
}
Seems like the code of the function given in your question does those 2 things in one go, which could be more efficient, but it looks really hard to read.似乎您问题中给出的 function 的代码在一个 go 中完成了这两件事,这可能会更有效率,但它看起来真的很难阅读。
It's easier if you just always copy it to an array of length 4.如果你总是将它复制到一个长度为 4 的数组中,那就更容易了。
public static int decodeInt(byte[] input, int length) {
length = java.lang.Math.min(4, length);
byte[] destination = new byte[4];
System.arraycopy(input, 0, destination, 4-length, length);
int value = java.nio.ByteBuffer.wrap(destination).getInt();
return value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.