Notifications
Clear all
[Closed] Signed short
Feb 02, 2010 9:52 pm
I am trying to read a big endian short but i can not get the value to be read as signed can someone tell me what is wrong with my code.
fn ReadBEShort fstream = (
short = readshort fstream#signed
short = bit.swapBytes short 2 1
return short
)
3 Replies
Feb 02, 2010 9:52 pm
Appears to work for me. Perhaps your file open isn’t correct?
fn ReadBEShort fstream = (
short = readshort fstream #signed
short = bit.swapBytes short 2 1
return short
)
(
f=fopen ((getdir #temp) + "foo.bin") "wb"
WriteShort f 0x0180
fclose f
f=fopen ((getdir #temp) + "foo.bin") "rb"
v = ReadBEShort f
fclose f
formattedprint v format:"04x"
)
This outputs:
“8001”
Feb 02, 2010 9:52 pm
Oh. I think I see what you are really after. Looks like you need to read it unsigned, swap, then sign extend it yourself.
fn ReadBEShort fstream = (
short = readshort fstream #unsigned
short = bit.swapBytes short 2 1
b = (bit.get short 16)
for i = 17 to 32 do short = bit.set short i b
return short
)
(
f=fopen ((getdir #temp) + "foo.bin") "wb"
WriteShort f 0x0180
fclose f
f=fopen ((getdir #temp) + "foo.bin") "rb"
v = ReadBEShort f
fclose f
print v
formattedprint v format:"08x"
)
This prints out
-32767
“ffff8001”