T
theosib
I'm writing a Ruby program that has to process binary data from files
and sockets. Data items are in bytes, 16-bit words, or 32-bit words,
and I cannot predict in advance whether the data will be msb-first or
lsb-first, so I end up writing things like this:
def unpack_16(x)
@msb_first ? ((x[0]<<8)|x[1]) : ((x[1]<<8)|x[0])
end
def pack_16(x)
y = "xx"
if (@msb_first)
y[0] = x>>8
y[1] = x&255
else
y[0] = x&255
y[1] = x>>8
end
end
I expect, however, that this will be painfully slow, and I can't
imagine that this hasn't been though of before. Is there a better way
to do this that will result in much better performance?
Thanks!
and sockets. Data items are in bytes, 16-bit words, or 32-bit words,
and I cannot predict in advance whether the data will be msb-first or
lsb-first, so I end up writing things like this:
def unpack_16(x)
@msb_first ? ((x[0]<<8)|x[1]) : ((x[1]<<8)|x[0])
end
def pack_16(x)
y = "xx"
if (@msb_first)
y[0] = x>>8
y[1] = x&255
else
y[0] = x&255
y[1] = x>>8
end
end
I expect, however, that this will be painfully slow, and I can't
imagine that this hasn't been though of before. Is there a better way
to do this that will result in much better performance?
Thanks!