Endianness and Hex Editor Values

December 20, 2024 note-to-self

Type "foobar" (no quotes) into a text file, open in a hex editor. 'b' will be hex '62' which translated to dec is '98', which is the ascii code for the letter 'b'. B's ascii code is 66, so the hex should be… 66/16 = 4 r2, so 42? (checked and YUP).

Check little or big endian (endianness) of an OS:

php -r "echo unpack('S', pack('v', 1))[1] === 1 ? 'little' : 'big';"

Most are going to be little, though. That's the most common.

PHP Pack:

# C is 'unsigned char'
php -r "echo unpack('C*', 114, 112);" # rp
php -r "print_r(unpack('C*', 'rp'));" [0 => 114, 1 => 112]

"S" format is "machine byte order" which is why that "unpack('S')" can work; 'v' is always little endian byte order, which will always be the same order. Cool trick.

php -r "print_r(unpack('S', pack('v', 1)));" # 1
php -r "print_r(unpack('S', pack('n', 1)));" # 256