0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much for your answer! I pored over that page yesterday and completely missed the fact that it treats the bytes as little endian. And your solution makes sense - take the total, shift it over by 1 byte, then add the current byte we're on. Brilliant. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.