Re: bytes_to_int

new topic     » goto parent     » topic index » view thread      » older message » newer message

Evan Marshall wrote:
> 
> Evan Marshall wrote:
> > 
> > your average Joe wrote:
> > > 
> > > basically, how can i convert a sequence like this
> > > 
> > > sequence = {199,235}
> > > 
> > > into a 2 byte signed integer
> > 
> > 
> > Doesn't
> > 
> > }}}
<eucode>
> > integer int
> > sequence = {199,235}
> > sequence = {199,235,0,0}
> > int = bytes_to_int(sequence)
> > bytes_to_int(sequence)
> > </eucode>
{{{

> > 
> > work?
> > 
> > I get 60359.
> 
> 
> or rather
> }}}
<eucode>
> sequence seq
> integer int
> 
> seq = {199,235}
> seq = {199,235,0,0}
> int = bytes_to_int(seq)
> > </eucode>
{{{


Actually, I think he wants to create a signed 16-bit integer. I'm not testing
this, but here is how I would do it:

-- tested
-- takes a two-element sequence in low-byte/hi-byte order
-- and returns a signed 16-bit integer
function bytes_to_short(sequence bytes)
    integer short

    if length(bytes) < 2 then
        if length(bytes) < 1 then short = 0 -- empty sequence
        else short = bytes[1]
        end if
        return short
    end if

    short = bytes[1] + 256 * bytes[2]
    if short > #7FFF then -- change sign
        short = and_bits(not_bits(short) + 1, #FFFF)
        short = -short
    end if

    return short
end function -- bytes to short

? bytes_to_short({127})      -- 127
? bytes_to_short({255, 127}) -- 32767
? bytes_to_short({0, 128})   -- (-1)
? bytes_to_short({255, 255}) -- (-32768)


More error checking could be added, such as making sure each element of bytes is
not greater than 255 (or using and_bits(bytes, #FF)).

You could also change this to take longer sequences and break them into two, or
(easily enough) take an atom and convert it to a 16-bit signed integer, etc.

If you need to reverse the byte-order, then just switch this statement:
short = bytes[1] * 256 + bytes[2]


HTH

--
"Any programming problem can be solved by adding a level of indirection."
--anonymous
"Any performance problem can be solved by removing a level of indirection."
--M. Haertel
j.

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu