Forum Discussion

jbrave's avatar
jbrave
Channel Surfer
14 years ago

littleEndian > byteArray> signed integer and back

I'm reading a 16 bit little-endian file into a byte array and then converting it to signed 16bit integers:

function readcontroldata(ba as object)
for i=0 to ba.count()-1
int16=(ba+(ba[i+1]*256))-32768
...
next i

This appears to be correct, but I'm not 100% certain I"m getting the sign right, the file is stored as 2's-complement signed integers from -32768 to 32767. I think I've got the byte order correct, but the guesswork is, do I just assemble the two bytes into one 16bit word as above, or is there some other thing I need to do with the sign?

Now that I have successfully loaded the file I want to convert it back to 16 bit little -endian and write it back to tmp:/

I think I need to make it a positive 16 bit integer again before writing back to disk? I suppose I could just add 32768 to it to reverse the process, but not 100% sure of this.

There is no >> function in brightscript (I know there is in LIbRokuDev).

I think if I extract the low byte:

Lowbyte=int16 and &h00FF

and then:

highbyte=(int16-lowbyte)/256

Is that correct?

I realize LibRokuDev implements some of this, just trying to figure out how to do it myself.

Also, does anyone know how the signs are stored in a 16bit signed integer on Roku?

- Joel

3 Replies

  • renojim's avatar
    renojim
    Community Streaming Expert
    I believe all integers are 32 bits and I also believe that isn't documented anywhere. So, there's no such thing as a 16-bit integer in Brightscript. You need to convert your signed 16-bit, 2's complement, values to signed 32-bit values. Your positive values will go from 0 to &h7FFF (0 to 32767) and your negative values will go from &hFFFF to &h8000 (-1 to -32768). So if the most significant bit is a one then your 16-bit number is negative. For the 32-bit equivalent, the 17 most significant bits will all be ones for a negative number.

    Here's the code:
    for i = 0 to ba.Count() - 1 step 2
    x = ba[i] + ba[i+1]*256
    if x > 32767 then x = x + &hFFFF0000 ' if x is >= 32768 then it's really a 16-bit negative number
    end for


    To convert back from a 32-bit number that goes from -32768 to +32767 is trivial:
    j = 0
    for i = 0 to numvals - 1
    ba[j] = x[i] and &hFF
    ba[j+1] = (x[i] and &FF00)/256
    j = j + 2
    end for


    Hope this helps!
    -JT
  • renojim's avatar
    renojim
    Community Streaming Expert
    Thanks! There's definitely things I really need to explore more thoroughly and those library source files are one of them.

    -JT
  • jbrave's avatar
    jbrave
    Channel Surfer
    Thanks JT, the read part is working well, I'll get to the write soon.

    - Joel