简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM