Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a signed integer to an unsigned integer in Ruby?

Tags:

ruby

I have a number that I received from a C program that came to me as a negative number:

-1771632774

It's supposed to be this number:

2523334522

I realized that this must be due to some conversion from an signed integer to an unsigned integer. Now that I have this negative number in Ruby, how can I convert it back to the unsigned version?

like image 959
Andrew Avatar asked Jul 09 '18 16:07

Andrew


People also ask

How do I change from signed to unsigned?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

Does Atoi work for unsigned int?

The simple answer is to use strtoul() instead. The longer answer is that even if all you needed was signed 32 bit integers or were happy with 31 bits for unsigned, the atoi() function is a poor fit for what you appear to be doing. As you have already noted, the atoi() function converts a string to an integer.

How do you convert to int in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

Which of the following method is used to convert a variable to integer in Ruby?

Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.


Video Answer


1 Answers

Put the negative integer in an array. Call pack with an argument of 'L' which represents "32-bit unsigned, native endian (uint32_t)". Call unpack with the same argument. Finally, get the number out of the array.

[-1771632774].pack('L').unpack('L').first
#=> 2523334522

http://ruby-doc.org/core-2.4.0/Array.html#method-i-pack

like image 120
Andrew Avatar answered Oct 12 '22 20:10

Andrew