[Closed] longswap ?
I try to parse a binary file.
I know that the file is a series of 16-bit big-endian words.
I am not sure what to do :argh:.
theFile = fopen myFile "rbS"
re_1 = ""
while re_1 != undefined do(
re_1 = (readlong theFile #signed)
if re_1 != undefined then (
format "%
" re_1
)
)
I try to “swap the words” with this:
fn longSwap s = (
b1 = bit.and s 255
b2 = bit.and (bit.shift s 8) 255
b3 = bit.and (bit.shift s 16) 255
b4 = bit.and (bit.shift s 24) 255
return ((bit.shift 24 b1) + (bit.shift 16 b2) + (bit.shift 8 b3) + b4)
)
But I get errors like this:
Runtime error: Bit index or shift count out of range: < -32 or > 32: 102
.
I I read just every second byte I get most of the data I need.
Some of the data wont show up right as the values are to big -> 16-bit words.
Maybe someone sees my error.
Or can point me to a “101 byteswapping for dummies like rdg”.
As I know know almost anything about endians, but don’t know how to use them …
Georg
Hi Georg,
I’m not very experienced in the subject but you can try :
re_1 = ReadShort theFile #signed
...
fn byteSwap nValue =
(
shiftRight = bit.shift nValue -8
shiftLeft = bit.shift nValue 8
-- Return
(bit.or shiftRight shiftLeft)
)
Maybe it’s better to use ReadShort than ReadLong.
Tell me if it works.
Hi.
You were shifting in the wrong direction when extracting the bytes (you were shifting to the left). Also, when building the long, you had the arguments swapped (that’s the reason MAX was telling you were causing overflow).
fn swapLong n = (
b1 = bit.and n 0xFF
b2 = bit.and (bit.shift n -8) 0xFF
b3 = bit.and (bit.shift n -16) 0xFF
b4 = bit.and (bit.shift n -24) 0xFF
return ((bit.shift b1 24) + (bit.shift b2 16) + (bit.shift b3 8) + b4)
)
EDIT:
by the way, here you have a function to print the actual bits of an integer. It could help to see better what it does the shift function.
fn printBinary n = (
for b = 31 to 0 by -1 do (
if ( (mod (b + 1) 4) == 0 and b != 0 and b != 31) do
format " "
format "%" (Bit.and (Bit.shift n -b) 1)
)
format "
"
)
Greets.
I’ve re-read your message and you want to swap a single word (16 bits)?. Then the function should be:
fn swapWord n = (
b1 = bit.and n 0xFF
b2 = bit.and (bit.shift n -8) 0xFF
return ((bit.shift b1 8) + b2)
)
To print the word:
fn printBinaryWord n = (
for b = 15 to 0 by -1 do (
if ( (mod (b + 1) 4) == 0 and b != 0 and b != 15) do
format " "
format "%" (Bit.and (Bit.shift n -b) 1)
)
format "
"
)
Thank you both!
I will try this right now.
I have a goog feeling.
Because:
I adopted the shortswap function I found in this forum.
The purpose of this function was to swap for writing the values.
I read the values – the swap was in the wrong direction.
Georg