[英]How to convert minus hex value to String and byte array
I want to convert decimal -10 value to hex in a String and byte array format. 我想将十进制-10值转换为字符串和字节数组格式的十六进制。
I have tried 我努力了
String minHex = Integer.toHexString(Integer.valueOf(-10));
System.out.println(minHex);
Which results in fffffff6 , and I think it is not correct. 结果为fffffff6 ,我认为这是不正确的。 And for converting byte array I am using below function which I found from
为了转换字节数组,我使用下面的函数,我从
Convert a string representation of a hex dump to a byte array using Java? 使用Java将十六进制转储的字符串表示形式转换为字节数组?
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
So also not sure it will work for minus hex value or not. 因此也不确定它是否适用于负十六进制值。
To convert an hex to a String
the way you expect it ie -10
is converted to -a
, use: 要将十六进制转换为
String
,即将-10
转换为-a
,请使用:
String hex = Integer.toString(-10, 16);
To convert to a byte
array, simply convert the int
to a byte
array, it is represented the same way: 要转换为
byte
数组,只需将int
转换为byte
数组,其表示方式相同:
byte[] bytes = ByteBuffer.allocate(4).putInt(-10).array();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.