Joakim Christiansen wrote:I just have to wonder...
Why is it that "long = $hex_here" actually reverses the hex code?
The short answer is that value of a number is stored differently in memory than the way it is written.
The long answer to your question is that you were putting/getting the values from memory in the wrong order.
This takes place due to Intel PC's using the Little Endian format to store integers in memory.
Code: Select all
The Little Endian order stores the bytes of an integer n memory
with the lowest valued byte first.
The Long (= $01020304) is stored at address $3000 like this:
Address : Value
$3000 : $04
$3001 : $03
$3002 : $02
$3003 : $01
You'll also see this crop up frequently when using constants for RGB values also. RGB stands for the way it is in memory (i.e. it's stored as RR GG BB), but if you supply a constant to one of PureBasic's drawing commands or poke it into memory directly as a Long you have to order the bytes correctly for the translation (i.e. $00BBGGRR).
Here's a version that doesn't reverse the byte-order of integers stored using a Little-Endian ordering:
Code: Select all
Procedure.s memoryToHex(Address,length) ;returns a string containing the hex representation of the memory area
Protected result$, i
For i=length-1 To 0 Step -1
result$ + RSet(Hex(PeekB(Address+i),#PB_Byte),2,"0")+" "
Next
ProcedureReturn result$
EndProcedure
Procedure hexToMemory(Address,hex$) ;converts hex into data
Protected i, pos, len
hex$ = RemoveString(hex$," ")
len = Len(hex$)
For i=len - 1 To 0 Step -2
PokeB(Address+pos,Val("$"+Mid(hex$,i,2)))
pos+1
Next
EndProcedure
long = $04030201
Debug memoryToHex(@long,4)
hexToMemory(@long,"04030201")
Debug memoryToHex(@long,4)
@Edit: removed the term 'correct' and replaced it with a more accurate description involving the 'endian-ness' .
