Reversing bytes

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm reading 16bit integers from a binary file and putting the values into a
spreadsheet. Unfortunately the binary file is big-endian, so all my extracted
integer values are wrong. What is the neatest way of reversing the bytes then
converting the number to an integer?

Grateful for help.
 
You can use DEC2BIN() to convert the value to a bit string(s), then use
MID()'s to separate the individual bits. Apply a conversion algorithm and
then re-construct the bits.
 
Thanks for this but I'd prefer to do the conversion in the code. If I read
the two bytes into a byte array with

Get #1, , read_two_bytes(2)
Get #1, , read_two_bytes(1)

is there a way of converting the byte array to the integer value?
 
One way, simple but not the fastest -

Dim ig As Integer

ig = "&H" & Right$("0" & read_two_bytes(2), 2) & _
Right$("0" & read_two_bytes(1), 2)

Assumes read_two_bytes(2) is the high value byte. Also 'read_two_bytes' is
never an empty string, but if it might be include "00", or if always two
characters you wouldn't need the Right functions.

Are you absolutely sure your values represent integers and not 2-byte longs.
If longs add an "&" to the end of the string, but only if truly longs (also
assign the value to a variable declared as Long or directly to cell).

Regards,
Peter T
 
The values read from the file are 16bit two's complement integers with most
significant byte first.

Solved it in the end with:

dim integer_value as long
dim integer_16bit as integer
dim read_two_bytes(1 to 2) as byte
Get #1, , read_two_bytes
integer_value = read_two_bytes(1) * CLng(256) + read_two_bytes(2)
If read_two_bytes(1) > 127 Then integer_16bit = integer_value - 2 ^ 16 Else
integer_16bit = integer_value
 
Ignore this!
wrongly assumed the bytes were written as hex instead (of course) as
numbers.

Peter T
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top