I wonder if I could ask for some advice regarding some work I'm currently doing.
I am working from a STANAG document which quotes the following:
ID numbers shall be formed as 4-byte numbers. The first (most significant) byte shall be the standard NATO country code for the object in question. Valid country codes shall range from 0 to 99 decimal... Country code 255 (hexadecimal FF) shall be reserved.
It then 开发者_JAVA技巧goes on to detail the three other bytes. In the specification, the ID is given the type Integer 4, where Integer n is a signed integer and n is 1,2, or 4 bytes.
My question, and I acknowledge this could be considered an ignorant question and I apologise, is that an integer is, as we know, 32 bits/4 bytes. How can "the first byte" be, for example, 99, when 99 is an integer?
I would greatly appreciate any clarification here.
An integer is normally 4 bytes. But if you store a small number like 99, the other three bytes store 8x 0-value bits. The spec is asking for you to use one integer storage (4-bytes) to store 4 different smaller numbers within its bytes.
The easiest way is probably to use a toInt function on an array of 4 bytes, e.g. (there is no byte[] length checking nor is this function tested - it is illustrative only)
public static final int toInt(byte[] b)
{
int l = 0;
l |= b[0] & 0xFF;
l <<= 8;
l |= b[1] & 0xFF;
l <<= 8;
l |= b[2] & 0xFF;
l <<= 8;
l |= b[3] & 0xFF;
return l;
}
byte[] bytes = new byte[] {99, 4, 9, 0};
int i = toInt(bytes, 0);
32-bits of an int
11110101 00000100 00001001 00000000
^byte ^byte ^byte ^byte
Each block of 8 bits in the int is enough to "encode"/"store" a smaller number. So an int
can be used to mash together 4 smaller numbers.
"99" is an integer number mathematically, but not necessarily an Integer
or int
from the Java perspective. The value 99 can be held by a short
, for instance (which is short for "short integer"), which is a 16-bit data type, or in a byte
, which is an 8-bit data type.
So basically, you'll want to look at their ID thing as a series of four byte
values. Beware that Java's byte
type is signed.
An integer (outside computing) just means any value without a decimal which includes 2, 99, -5, 34134, 427391471244211, etc. In computing terms, an integer is (traditionally) a 32-bit number that can contains any value that will fit in it. Each byte (8 bits) of that (computing) integer value is also an individual (numerical) integer between 0 and 255.
精彩评论