Question

I am using Leemon Baird's BigInt.js (documentation) to handle big integers. I need to be able to arrive to the same integer from BigInt into Ruby.

Example JS file:

var number = "1234567890987654321";
var bigNumber = str2bigInt(number, 10, 80); //10: input = Decimal
var bigNumber64 = bigInt2str(bigNumber, 64); //64: ouput = Base64
console.log(bigNumber64);
//--> 14Y4FInR1on

Example Ruby file:

big_number_64 = '14Y4FInR1on'
big_number = Base64.decode64(big_number_64) #input: Base64: output: decoded string
big_number = big_number.unpack('B*').first #B*: output = Binary
big_number = big_number.to_i(2) #read big_number as binary, output = integer
puts big_number
#--> 26313825004518719100904402231695296969994

My problem is that I need this to be equal

1234567890987654321 != 26313825004518719100904402231695296969994

I've tried

big_number = big_number_64.unpack('m*').first.unpack('B*').first

And tried reversing the process and checking Base64 == Base64 instead of Decimal == Decimal, and I can't seem to still make them equal.

Please help.

Was it helpful?

Solution

When you pass the parameter through Ajax, it's just a string. All you need is a format that Ruby can understand and cast to an integer.

Ruby understands integers of arbitrary length, so you can send it as 1234567890987654321 and call to_i.

If you're interested in reducing the length of the string representation, you could convert it to base 36 (the highest base that Ruby can interpret) like this:

JS

var number = "1234567890987654321";
var bigNumber = str2bigInt(number, 10, 80); //10: input = Decimal
var bigNumber36 = bigInt2str(bigNumber, 36); //36: output = Base 36
console.log(bigNumber36);
//---> "9do1sjhjpei9"

Ruby

big_number_36 = '9do1sjhjpei9'
big_number = big_number_36.to_i(36)
puts big_number
# => 1234567890987654321
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top