skiffr
skiffr

Reputation: 3

Best way to convert three bytes to an unsigned integer, from a binary file?

What is the best way to convert three bytes to an unsigned integer, from a binary file?

This is my current solution, do you know a better one?

a, b, c = file.read(3).unpack("C*")
a << 16 | b << 8 | c

Upvotes: 0

Views: 472

Answers (3)

Bill
Bill

Reputation: 21

Use the BinData gem

require 'bindata'
n = BinData::Uint24be.read(file)

Upvotes: 2

mu is too short
mu is too short

Reputation: 434585

You could do it all with unpack if you didn't mind added an extra byte yourself:

n = *("\x00" + file.read(3)).unpack('N')

I don't know if that qualifies as better, that's pretty subjective.

Upvotes: 0

Casper
Casper

Reputation: 34308

Ooh..fun:

file.read(3).unpack("C*").inject { |r, n| r << 8 | n }

Upvotes: 1

Related Questions