There is a hex byte sequence: 04 9A 01 00 The HxD hex editor decodes them as "104964" (UInt 32 Little Endian). I need to implement a similar conversion in Delphi 7, but in the opposite direction: so that the number 104964 turns into 04 9A 01 00 (i.e. with this flipping of Hex bytes, because the usual calculator thinks that this is "19A04") .
Asked
Active
Viewed 271 times
1 Answers
1
If you want to do that unbound to the CPU architecture you're in then you create each byte by simple arithmetics:
var
iNumber: Cardinal; // Input value: 32 bit unsigned
aHex: Array[1.. 4] of Byte; // Output of raw bytes
begin
iNumber:= 104964;
aHex[1]:= iNumber and $FF; // First 8 of 32 bit
aHex[2]:= (iNumber shr 8) and $FF; // Next=higher 8 bit...
aHex[3]:= (iNumber shr 16) and $FF;
aHex[4]:= (iNumber shr 24) and $FF; // ...last=highest 8 bit
Caption:= IntToHex( aHex[1], 2 )+ ' '
+ IntToHex( aHex[2], 2 )+ ' '
+ IntToHex( aHex[3], 2 )+ ' '
+ IntToHex( aHex[4], 2 ); // Converting to text
end;
However, if you know that you're already on a LE architecture (Windows) then you can directly access your variable per byte, because in memory it is already in Little Endian:
var
iNumber: Cardinal; // Input value
aHex: Array[1.. 4] of Byte absolute iNumber; // Input as raw bytes
begin
iNumber:= 104964;
Caption:= IntToHex( aHex[1], 2 )+ ' '
+ IntToHex( aHex[2], 2 )+ ' '
+ IntToHex( aHex[3], 2 )+ ' '
+ IntToHex( aHex[4], 2 ); // Converting into text
end;

AmigoJack
- 5,234
- 1
- 15
- 31
-
1I haven't seen the construct of tying the hex array to the Cardinal with `absolute iNumber` before ... I'm glad I had a more detailed look at your answer! – Rob Lambden Aug 17 '22 at 07:43