我有crc16计算方法:
private static final int POLYNOMIAL = 0x0589;
private static final int PRESET_VALUE = 0xFFFF;
private static byte[] data = new byte[512];
public static int crc16(byte[] data){
int current_crc_value = PRESET_VALUE;
for (int i = 0; i < data.length; i++){
current_crc_value ^= data[i] & 0xFF;
for (int j = 0; j < 8; j++ ) {
if ((current_crc_value & 1) != 0) {
current_crc_value = (current_crc_value >>> 1) ^ POLYNOMIAL;
}
else{
current_crc_value = current_crc_value >>> 1;
}
}
if ((i+1)%64==0) {
System.out.println("\nValue: \t"+(~current_crc_value & 0xFFFF));
}
}
current_crc_value = ~current_crc_value;
return current_crc_value & 0xFFFF;
}
在crc16方法中传递data []数组后,它将crc值(已计算)System.out.println("\nValue: \t"+(~current_crc_value & 0xFFFF));
打印为:
Value: 64301
Value: 63577
Value: 65052
Value: 63906
Value: 65223
Value: 65369
Value: 63801
Value: 64005
但实际上我希望它以HEX格式显示为0x....
我也可以看到值实际上是 5位但这需要是16位crc值,我也可以看到所有这些都具有相同的MSB,即 6 。我应该省略这个价值吗?
我认为这是一个有点愚蠢的问题,但我们将不胜感激。
答案 0 :(得分:0)
通常当您需要以特定格式输出变量时,可以使用String.format()
来实现此目的:
System.out.println(String.format("\nValue: \t0x%x", ~current_crc_value & 0xFFFF));
%x
是十六进制格式。0x
只是一个简单的字符串答案 1 :(得分:0)
您可以尝试使用Integer.toHexString(int)
像
这样的东西int val = 12345;
String hex = Integer.toHexString(val);
并让他们回来试试这个:
int i = (int) Long.parseLong(hex, 16);