我需要在Java中将整数值更改为2位十六进制值。是否有任何方法可以实现这一点。 谢谢
我的最大数字将是63,最小数字将是0。 我想对小值添加前导零。
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
请注意,这可能会给你超过2位数!(一个整数是4个字节,所以你可能会得到8个字符。)
如果您确定您只处理单字节值(255或更少),这里有一个小技巧可以获得填充:
Integer.toHexString(0x100 | 42).substring(1)
更多(且更好)的解决方案,请参见Java中用零进行整数左填充(非十进制格式)。
String.format("%02X", (0xFF & value));
使用Integer.toHexString()
。如果只有一位数字,请不要忘记在前面添加一个零。如果您的整数大于255,则会获得两个以上的数字。
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
StringBuilder
真的是一种改进吗?http://pastebin.com/KyS06JMz - just lerningfor(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
String.format("0x%08X", 20) //print 0x00000014
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}