0

I have crc16 calculation method:

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;
    }

After passing data[] array in the crc16 method, It prints the crc value (calculated) System.out.println("\nValue: \t"+(~current_crc_value & 0xFFFF));as:

Value:  64301

Value:  63577

Value:  65052

Value:  63906

Value:  65223

Value:  65369

Value:  63801

Value:  64005

But actually i want it in HEX format as 0x.... Also i can see that the Value is actually 5 digit but this need to be 16 bit crc value, also i can see that all of them has same MSB i.e 6. Should i omit that value?

I think this is kind of silly question but help would be appreciated.

Ganesh Pandey
  • 5,216
  • 1
  • 33
  • 39

2 Answers2

0

Usually when you need to output variables in a specific format, you can use String.format() for that purpose:

System.out.println(String.format("\nValue: \t0x%x", ~current_crc_value & 0xFFFF));
  • %x is the hexadecimal format.
  • 0x is just a plain string here
Joffrey
  • 32,348
  • 6
  • 68
  • 100
0

You can simply try using Integer.toHexString(int)

Something like

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

and to get them back try this:

int i = (int) Long.parseLong(hex, 16);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331