Converting from Byte array to int

BlitzMax Forums/BlitzMax Beginners Area/Converting from Byte array to int

DH(Posted 2009) [#1]
I know there is a method or something where I can take a 4 element byte array and make an int out of it. These docs are horrible!

Any ideas?


GfK(Posted 2009) [#2]
Like this?
Strict

Local a:Byte[4]

a[0] = $ff
a[1] = $20
a[2] = $7C
a[3] = $a0

Print Hex(byteArrayToInt(a))

Function byteArrayToInt:Int(array:Byte[])
	Local result:Int
	
	For Local n:Int = 0 To 3
		result:+(array[n] Shl ((3-n) * 8))
	Next
	Return result
End Function



DH(Posted 2009) [#3]
K, so no short-hand way to do it....

Thanks GFK! I appreciate the answer, I was trying to avoid having to write it out to do the conversion (as so many other non-basic languages have it built-in as a function).


Brucey(Posted 2009) [#4]
Like this?

Heh... interesting :-)

Strict

Local a:Byte[4]

a[0] = $ff
a[1] = $20
a[2] = $7C
a[3] = $a0

Print Hex(byteArrayToInt(a))

Function byteArrayToInt:Int(array:Byte[])
	Return Int Ptr(Byte Ptr(array))[0]
End Function


Note the endianness in the result though. You'd need to be on PPC to get the same byte order appearance.


GfK(Posted 2009) [#5]
Heh... interesting :-)
True wisdom is knowing that you don't know everything.


Brucey(Posted 2009) [#6]
I've just been using it a lot recently :-)

My wisdom is knowing that I once wrote some code to do it, but I'm buggered if I can remember what it was :-p


GW(Posted 2009) [#7]
I had to do this for my bf JIT.
Sometimes keeping track of all the int,float,byte,var ptr [0] combinations gets confusing. Moving from int to pointer and back. Some things only work when converted to a byte ptr first.


ImaginaryHuman(Posted 2009) [#8]
Print int ptr(varptr(a[0]))[0] is also a possibility, but much the same