【问题标题】:Convert int type to HEX equivalent in Java? [duplicate]在 Java 中将 int 类型转换为 HEX 等价物? [复制]
【发布时间】:2015-06-17 00:09:54
【问题描述】:

我有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 &amp; 0xFFFF));as:

Value:  64301

Value:  63577

Value:  65052

Value:  63906

Value:  65223

Value:  65369

Value:  63801

Value:  64005

但实际上我希望它是十六进制格式 0x.... 我也可以看到该值实际上是 5 位 但这需要是 16 位 crc 值,我也可以看到所有它们具有相同的 MSB,即 6。我应该省略那个值吗?

我认为这是一个愚蠢的问题,但我们将不胜感激。

【问题讨论】:

    标签: java hex byte


    【解决方案1】:

    您可以简单地尝试使用Integer.toHexString(int)

    类似

    int val = 12345;
    String hex = Integer.toHexString(val);
    

    让他们回来试试这个:

    int i = (int) Long.parseLong(hex, 16);
    

    【讨论】:

      【解决方案2】:

      通常当您需要以特定格式输出变量时,您可以为此目的使用String.format()

      System.out.println(String.format("\nValue: \t0x%x", ~current_crc_value & 0xFFFF));
      
      • %x 是十六进制格式。
      • 0x 在这里只是一个普通字符串

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 2021-12-26
        • 2020-06-26
        • 1970-01-01
        相关资源
        最近更新 更多