3

I need help to create the header as explain below, I am not confident with byte conversion and big endian convention.

I think my problem comes from the lines byte[] VERSION = "01".getBytes(); I don't know how to 'force' the String to be stored in one byte.

Header creation

public static final int HEADER_SIZE = 8;
byte[] header = new byte[HEADER_SIZE];

// Header struture
/*
*byte 0   : Version
*byte 1   : Inverse Version
*byte 2-3 : Type
*byte 4-7 : Length
*/

// Hex values
byte[] VERSION = "01".getBytes();
byte[] INVERSE_VERSION = "FE".getBytes();
byte[] TYPE = "9000".getBytes();
byte[] LENGTH = "02".getBytes();

ByteBuffer buf = ByteBuffer.wrap(this.header);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.put(VERSION);
    buf.put(INVERS_VERSION);
    buf.put(TYPE);
    //buf.put(LENGTH); <-- Overflow

//out
System.out.println(new String(buf.array(), "ASCII"));

Actual Output

01FE9000

Output Expected

01FE900020000000
5
  • 1
    did you missed this code byte[] LENGTH = "02".getBytes(); Commented Mar 23, 2015 at 11:49
  • 1
    how do you expect this 01FE900000000002 and not this 01FE900002000000? Commented Mar 23, 2015 at 12:14
  • Hexadecimal is a representation, not a data type. Commented Mar 23, 2015 at 12:41
  • public static void main(String[] args){ long hex1 = 0x01; long hex2 = 0xFF; long hex3 = 0x9000; long hex4 = 0x20000000; long hexResult = hex4 | (hex3<<32) | (hex2<<(32+16)) | (hex1<<(32+16+8)); String S_result_unpadded = Long.toHexString(hexResult); System.out.println("Hex string unpadded : " + S_result_unpadded); String S_result_padded = String.format("%16s", S_result_unpadded).replace(' ', '0'); System.out.println("Hex string unpadded : " + S_result_padded); } Commented Mar 23, 2015 at 13:53
  • Since I can't post an answer I posted here what helped me after few experiments... Commented Mar 23, 2015 at 13:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.