About Monkey 2 › Forums › Monkey 2 Programming Help › Convert int endian
This topic contains 3 replies, has 3 voices, and was last updated by
Hezkore
1 year, 10 months ago.
-
AuthorPosts
-
May 23, 2017 at 9:12 pm #8245
I’m trying to read some older file formats, but I need to be able convert my integers (which I get via PeekInt from a DataBuffer) from Big Endian to Little Endian and vice versa.
Are there any functions for this?
I’m so bad at searching the docs, I can’t even find a function for displaying values as binary.
BlitzMax had Bin() I believe.May 23, 2017 at 11:26 pm #8246DataBuffer has a ByteOrder property, which can even be set from the ctor, eg:
Monkey12Local buf:=New DataBuffer( 1024,ByteOrder.BigEndian ) 'create a big endian databuffer.buf.ByteOrder=ByteOrder.LittleEndian 'changed my mind!Kind of untested as I’ve never used them in real code yet. I will probably add some general purpose endian functions to byteorder.monkey2 one of these days too..
I can’t even find a function for displaying values as binary.
Try ULongToString and StringToULong. I will probably add Hex, Bin etc on day too as I find these hard to rember myself.
May 24, 2017 at 7:44 pm #8253A class for swapping big/little endian from/to native format. Just create an instance of the class and call endian.swapEndian(n:int, original:Int) where n is the number to convert and original is the byte order you are converting from/to. Nice thing is, the same method is used in each case. pass the int you wish to save followed by the ByteOrder value you are saving to, or pass the value you just read followed by the stored ByteOrder .
Monkey123456789101112131415161718192021222324252627282930313233343536373839#Import "<std>"Using std..Class EndianField endian:IntMethod New()Local a:Int = $AABBCCDDIf UByte Ptr(Varptr a)[0] = $AAendian = ByteOrder.BigEndianElseendian = ByteOrder.LittleEndianEndEndMethod swapEndian:Int(n:Int, original:Int)If endian = original Then Return nReturn ((n & $FF000000) Shr 24) | ((n & $FF0000) Shr 8) | ((n & $FF00) Shl 8) | ((n & $FF) Shl 24)EndEndFunction Main()Local endian := New EndianLocal a:Int = $AABBCCDD 'Load a with a valuePrint "Value of a = "+Hex(a)Local be:String = Hex(endian.swapEndian(a,ByteOrder.BigEndian)) 'save a as big endianLocal le:String = Hex(endian.swapEndian(a,ByteOrder.LittleEndian)) 'save a as little endianPrint "be = "+be+"~nle = "+le 'print the contents of be and leLocal b:Int = endian.swapEndian(FromHex(be),ByteOrder.BigEndian) 'load from big endianLocal c:Int = endian.swapEndian(FromHex(le),ByteOrder.LittleEndian) 'load from little endianPrint "~nb = "+Hex(b)+"~nc = "+Hex(c) 'both should be the sameendMay 25, 2017 at 1:35 pm #8254 -
AuthorPosts
You must be logged in to reply to this topic.