K
Kim Pedersen
Hi,
I have some data with binary numbers.
e.g. a 3 byte string could be 0x01216f which is 74095 decimal.
To do this conversion in ruby I've come up with:
def binum(bs)
n = e = 0
bs.reverse.each_byte do |c|
n += c * 256 ** e
e += 1
end
n
end
bs = ''
bs << 0x01 << 0x21 << 0x6f
puts binum(bs) => 74095
Now some data are signed binary numbers stored as two's complement.
e.g. 0xfede91 which is -74095 decimal.
How can I do this conversion in ruby?
Best regards,
Kim
I have some data with binary numbers.
e.g. a 3 byte string could be 0x01216f which is 74095 decimal.
To do this conversion in ruby I've come up with:
def binum(bs)
n = e = 0
bs.reverse.each_byte do |c|
n += c * 256 ** e
e += 1
end
n
end
bs = ''
bs << 0x01 << 0x21 << 0x6f
puts binum(bs) => 74095
Now some data are signed binary numbers stored as two's complement.
e.g. 0xfede91 which is -74095 decimal.
How can I do this conversion in ruby?
Best regards,
Kim