Argus9
Argus9

Reputation: 1945

Ruby: Convert Byte Array to Integer?

I am trying to duplicate this snippet of C# code in Ruby:

var guid = Guid.Parse("a823efd8-c8c1-4cf5-9aad-3b95d6f11371");
byte[] a = guid.ToByteArray();
var bigInteger = new BigInteger(a, isUnsigned: true);

I've gotten as far as creating the byte array with help from this answer:

guid = 'a823efd8-c8c1-4cf5-9aad-3b95d6f11371'
parts = guid.split('-')
mixed_endian = parts.pack('H* H* H* H* H*')
big_endian = mixed_endian.unpack('L< S< S< A*').pack('L> S> S> A*')
byte_array = big_endian.bytes
#=> [216, 239, 35, 168, 193, 200, 245, 76, 154, 173, 59, 149, 214, 241, 19, 113]

I'm not sure what to do to convert this array of bytes into an integer - line 3 of the C# example above. Can anyone help me figure out what to do?

Upvotes: 0

Views: 496

Answers (1)

matt
matt

Reputation: 79723

The straightforward way would be to just do the calculation. The C# code is actually treating the bytes as little endian, which is why we reverse the array first here:

byte_array.reverse.inject(0) {|m, b| (m << 8) + b }

(This gives me 150306322225734326370696054959344185304 with your input.)

I don’t think there is a direct method to convert a binary string or an array of bytes to an integer. I suspect that any more efficient way would need to have the internal representation of the integer exposed.

Upvotes: 3

Related Questions