Surbhi Jain
Surbhi Jain

Reputation: 369

why does the following code prints a byte as an integer?

Shouldn't address.getAddress())[2]) be printing in 0-1 or byte format because it itself is a byte. Why is it printing -126?

public static void main(String s[]) {
    try {
        String arg="www.google.com";
        InetAddress address = InetAddress.getByName(arg);
        System.out.println("Address: " + (address.getAddress())[2]));
    } catch (UnknownHostException exc) {
        System.out.println(exc);
    }
}

Upvotes: 0

Views: 73

Answers (2)

chiastic-security
chiastic-security

Reputation: 20520

In Java, a byte is an 8-bit signed integer. This means that it can take values from decimal -128 to decimal +127.

When you say byte format, you might mean an unsigned value from 0 to 255. If you want to use a byte b as an unsigned value, you should use b & 0xff.

If what you're trying to do is print the byte as a two-character hex string, you should use

String.format("%02X", b)

Upvotes: 1

Eran
Eran

Reputation: 393771

The values of bytes in Java are from -128 to 127. -126 is a valid byte value.

Upvotes: 0

Related Questions