Ephemera
Ephemera

Reputation: 8980

Ensuring variable size for bitwise operations in Ruby

I have a group of hex values that describe an object in ruby and I want to string them all together into a single bit bucket. In C++ I would do the following:

int descriptor = 0 // or uint64_t to be safe
descriptor += (firstHexValue << 60)
descriptor += (secondHex << 56)
descriptor += (thirdHex << 52)
// ... etc
descriptor += (sixteenthHex << 0)

I want to do the same thing in Ruby, but as Ruby is untyped, I am worried about overflow. If I try and do the same thing in Ruby, is there a way to ensure that descriptor contains 64 bits? Once the descriptors are set, I don't want to suddenly find that only 32 bits are represented and I've lost half of it! How can I safely achieve the same result as above?

Note: Working on OS X 64bit if that is relevant.

Upvotes: 0

Views: 119

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230386

Ruby has unlimited integers, so don't worry about that. You won't lose a single bit.

a = 0

a |= (1 << 200)

a # => 1606938044258990275541962092341162602522202993782792835301376

Upvotes: 4

Related Questions