Short toHexString

后端 未结 5 1668
别那么骄傲
别那么骄傲 2021-02-19 14:54

There are methods Integer.toHexString() and Long.toHexString(). For some reason they didn\'t implement Short.toHexString().

What

相关标签:
5条回答
  • 2021-02-19 15:16

    Yes, you can simply take the two least-significant bytes.

    This is a basic feature of the Two's Complement representation.

    0 讨论(0)
  • 2021-02-19 15:30

    This should also work for a short

    UnicodeFormatter.charToHex((char)c);
    

    You can download UniocdeFormatter.java here: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/i18n/text/examples/UnicodeFormatter.java

    0 讨论(0)
  • 2021-02-19 15:32

    You can convert your Integer.toHexString in to a hex string for short value.

    Integer is of 32 bit, and Short is of 16 bit. So, you can just remove the 16 most significant bit from Hex String for short value converted to integer, to get a Hex String for Short.

    Integer -> -33 = 11111111 11111111 11111111 11011111  == Hex = ffffffdf
    Short   -> -33 =                   11111111 11011111  == Hex =     ffdf
    

    So, just take the last 4 characters of Hex String to get what you want.

    So, what you want is: -

    Short sh = -33;
    String intHexString = Integer.toHexString(sh.intValue());
    String shortHexString = intHexString.substring(4);
    

    I think that would work.

    0 讨论(0)
  • 2021-02-19 15:33

    Not the simplest way to do this, but I you can get it done by converting to a byte array then converting that to a hex string.

     short a = 233;
     byte[] ret = new byte[2];
    
     ret[0] = (byte)(a & 0xff);
     ret[1] = (byte)((a >> 8) & 0xff);
    
     StringBuilder sb = new StringBuilder();
     for (byte b : ret) {
        sb.append(String.format("%02X ", b));
     }
    

    I think that will pretty much do it.

    0 讨论(0)
  • 2021-02-19 15:36

    If in your system short is represented as 16Bit you can also simply do the following.

    String hex = Integer.toHexString(-33 & 0xffff);
    
    0 讨论(0)
提交回复
热议问题