如何在Ruby中将负整数转换为二进制

Nob*_*oka 5 ruby binary integer type-conversion

问题1:我找不到以下列方式将负整数转换为二进制的方法.我应该像这样转换它.

-3 => "11111111111111111111111111111101"
Run Code Online (Sandbox Code Playgroud)

我试过以下:

sprintf('%b', -3) => "..101" # .. appears and does not show 111111 bit.

-3.to_s(2) => "-11" # This just adds - to the binary of the positive integer 3.
Run Code Online (Sandbox Code Playgroud)

问题2:有趣的是,如果我使用在线转换器,它告诉我-3的二进制是"00101101 00110011".

"11111111111111111111111111111101"和之间有什么区别"00101101 00110011"

fal*_*tru 9

包装然后拆包将转换-34294967293(2 32 - 3):

[-3].pack('L').unpack('L')
=> [4294967293]
Run Code Online (Sandbox Code Playgroud)
sprintf('%b', [-3].pack('L').unpack('L')[0])
# => "11111111111111111111111111111101"

sprintf('%b', [3].pack('L').unpack('L')[0])
# => "11"
Run Code Online (Sandbox Code Playgroud)