Convert Big Endian to Little

I need to byte swap some hex values by reading a binary file and then out putting the result in a file

For example

Convert this

00001D08 000084D0

To this:

081D0000 D0840000

I am just very confused on how to do this. I looked at the memoryblock functions but I have no idea what to do.

Well, if you have data in memoryblock, this looks like you just use UInt32Value() and switch LittleEndian property between read/write.

Or does it come as hex values?
I assume the file is in binary format.

I don’t understand how to put the contents of the input file into a memoryblock in the first place. When I try to put a hex value into the MemoryBlock I get a Type Mismatch error.

Something like this:

[code]// the file to use
dim f as FolderItem = SpecialFolder.Desktop.Child(“input.txt”)
// open it
dim b as BinaryStream = BinaryStream.Open(f)
// read all content
dim s as string = b.Read(b.Length)
// convert to MemoryBlock
dim m as MemoryBlock = s

// swap via MBS plugin
m.SwapBytes32MBS 0, m.size

// write to file
f = SpecialFolder.Desktop.Child(“output.txt”)
b = BinaryStream.Create(f, true)
b.Write m[/code]

This uses SwapBytes32MBS method in our MBS Xojo Plugins.

You can do this without a plugin too.

An important bit is that a MemoryBlock will auto-convert to a string and back, or you can instantiate one like a class. If you need to swap Int32 values, this will do it.

dim mb1 as MemoryBlock = bStream.Read( bStream.Length ) // All into the first MB
dim mb2 as new MemoryBlock( mb1.Size ) // A second MB of the same size
mb2.LittleEndian = not mb1.LittleEndian // Switch the endianness

for byteIndex as integer = 0 to mb1.Size - 1 step 4
  mb2.UInt32Value( byteIndex ) = mb1.UInt32Value( byteIndex )
next

newBStream.Write mb2 // Write out the value of mb2

(This code has not been tested.)

This assumes that your file will fit into memory. If not, you can do this in chunks.

Edit: Should have been UInt32Value, not Int32Value.