There are methods Integer.toHexString()
and Long.toHexString()
. For some reason they didn\'t implement Short.toHexString()
.
What
Yes, you can simply take the two least-significant bytes.
This is a basic feature of the Two's Complement representation.
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
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.
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.
If in your system short
is represented as 16Bit you can also simply do the following.
String hex = Integer.toHexString(-33 & 0xffff);