简体   繁体   English

为什么以下代码将字节打印为整数?

[英]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. address.getAddress())[2])不应以0-1或字节格式打印,因为它本身就是一个字节。 Why is it printing -126? 为什么打印-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);
    }
}

In Java, a byte is an 8-bit signed integer. 在Java中, byte是8位有符号整数。 This means that it can take values from decimal -128 to decimal +127. 这意味着它可以接受从十进制-128到十进制+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 . 当说字节格式时 ,可能表示0到255之间的无符号值。如果要将byte b用作无符号值,则应使用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)

Java中的字节值从-128到127。-126是有效字节值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM