【问题标题】:How to display a hex/byte value in Java如何在 Java 中显示十六进制/字节值
【发布时间】:2015-06-15 17:36:12
【问题描述】:
int myInt = 144;
byte myByte = /* Byte conversion of myInt */;

输出应该是myByte : 90(十六进制值144)。

所以,我做到了:

byte myByte = (byte)myInt;

我得到了myByte : ffffff90 的输出。 :(

我怎样才能摆脱那些ffffffs?

【问题讨论】:

  • 为什么应该是90?你没有在那里进行十六进制转换。值 144 超出 byte 范围并将溢出,因此该值(负数)。
  • 不幸的是,这现在被标记为错误问题的重复,因为问题不是关于如何将 int 转换为 byte(尽管标题不正确),而是关于如何在将byte 转换回int 时去掉额外的 1 位。投票重新开放 - 也许它可以作为更合适问题的副本而关闭。
  • 如果我搞砸了,我很抱歉 :),我是一名 C++ 开发人员和 java 新手,在 C++ 中我知道如何做到这一点,int -> unsigned int -> unsigned char,但是在 JAVA 中我真的很困惑。

标签: java int hex byte


【解决方案1】:

byte 是有符号类型。它的值在 -128 到 127 的范围内; 144 不在此范围内。 Java 中没有无符号字节类型。

如果您使用的是 Java 8,将其视为 0 到 255 范围内的值的方法是使用 Byte.toUnsignedInt

String output = String.format("%x", Byte.toUnsignedInt(myByte));

(我不知道你如何格式化十六进制输出的整数。没关系。)

Pre-Java 8,最简单的方法是

int byteValue = (int)myByte & 0xFF;
String output = String.format("%x", byteValue);

但在您执行上述任一操作之前,请确保您确实想要使用byte。很有可能你不需要。如果你想表示值 144,你不应该使用byte,如果你不需要的话。只需使用int

【讨论】:

    【解决方案2】:

    谢谢@ajb 和@smit,我用了两个答案,

    int myInt = 144;
    
    byte myByte = (byte) myInt;
    
    char myChar = (char) (myByte & 0xFF);
    
    System.out.println("myChar :"+Integer.toHexString(myChar));
    

    o/p,

    myChar : 90
    

    【讨论】:

      【解决方案3】:

      使用以下code

      int myInt = 144;
      byte myByte = (byte)myInt;
      System.out.println(myByte & 0xFF);
      

      在 Java 8 中,如 ajb 所说,使用Byte.toUnsignedInt(myByte)

      【讨论】:

        猜你喜欢
        • 2012-01-04
        • 2015-01-14
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-08
        • 2013-10-21
        相关资源
        最近更新 更多