According to the getOctets() description: “bytes must be interpreted as unsigned for correct values”.

What exactly does this mean?

Since it returns a byte value, the range is -128 to 127 (256 in total). Does this mean that if we have an ip address 255.255.255.255, then a byte array consisting of {127,127,127,127} should be returned or am I misunderstanding something?

No.

A byte in Java is a sequence of 8 bits. When doing arithmetic on these, Java says that the results are consistent with a two’s complement interpretation of the byte as a number. So if `a`

represents A in two’s complement, and `b`

represents B in two’s complement, then `a+b`

represents A+B in two’s complement, if it is representable.

For example, if A = -4, then `a = 0b11111100`

, and if B = 3, then `b = 0b00000011`

, so `a+b = 0b11111111`

, as A + B = -1. This should be obvious.

However, here we do not care about this, and instead say that the sequence of bytes, interpreted unsigned(ly), must represent the numbers from the IP address. Since 255 as an unsigned binary number is `0b11111111`

, the byte array in your example should be `[0b11111111, 0b11111111, 0b11111111, 0b11111111]`

. In Java, this could be written as `[-1, -1, -1, -1]`

, but since that is rather confusing, you might write it differently. For example, as `[(byte) 255, (byte) 255, (byte) 255, (byte) 255]`

.

2 Likes

So, just to be sure:

if my host is equal to `255.255.255.255`

, the following code would be sufficient?

```
// Host: 255.255.255.255
/* Parse URL, get URI, get Host, ... */
byte[] arr = getIPv4Octets(host);
byte[] exp = {(byte)255, (byte)255, (byte)255, (byte)255};
/* Arrays.equals comparison here ... */
```

~~Ignoring the fact that this is not how you denote arrays in Java,~~ Yes.

1 Like

alright thanks!

well, VSCode told me to use `{}`

, it marked `[]`

as error

Your code above is correct (with curly brackets).

I think Johannes was referring to another style of array initialization.

Java is pretty free about the syntax you use:

You can write `byte[] a`

or `byte a[]`

and `{...}`

or `new byte[]{...}`

:

Reference links:

1 Like