Four integers in four bytes?

I wonder if I can ask for advice regarding some of the work that I am currently doing.

I work from a STANAG document that quotes the following:

Identification numbers must be configured as 4-byte numbers. The first (most significant) byte is the standard NATO country code for the object in question. Valid country codes must be between 0 and 99 decimal ... Country code 255 (hexadecimal FF) must be reserved.

He then describes three other bytes in detail. The specification ID is assigned the type Integer 4, where Integer n is a signed integer and n is 1.2 or 4 bytes.

My question is, and I admit that this can be considered an uninformed question, and I apologize, is that the integer is known to be 32 bits / 4 bytes. How can the “first byte” be, for example, 99, when 99 is an integer?

I would really appreciate any clarification.

+4
source share
3 answers

An integer is usually 4 bytes. But if you store a small number, such as 99, the other three bytes contain 8x 0-digit bits. The specification asks you to use one integer storage (4 bytes) to store 4 different smaller numbers in its bytes.

The easiest way is probably to use the toInt function in an array of 4 bytes, for example. (checking byte length [] is not checked and this function is not checked - this is just an illustration)

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-bit int

 11110101 00000100 00001001 00000000 ^byte ^byte ^byte ^byte 

Each block of 8 bits in int is enough to "encode" / "save" a smaller number. So int can be used to crush 4 smaller numbers.

+4
source

"99" is an integer mathematically, but not necessarily Integer or int from a Java perspective. A value of 99 may be held, for example, by short (which is short for a “short integer”), which is a 16-bit data type, or byte , which is an 8-bit data type.

So basically you want to look at your identification thing as a series of four byte values. Remember that Java byte type is signed.

+3
source

An integer (outside of calculations) means only any value without a decimal number, which includes 2, 99, -5, 34134, 427391471244211, etc. In computational terms, an integer (traditionally) is a 32-bit number that can contain any value that fits into it. Each byte (8 bits) of this (computational) integer value is also an individual (numerical) integer from 0 to 255.

+1
source

Source: https://habr.com/ru/post/1337131/


All Articles