Question

Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as 96. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as 0140. Hexadecimal based numbers are usually prefixed by 0x: 96 would be written as 0x60.

The question is: can I write numbers as binary literals in Ruby? How?

Was it helpful?

Solution

use 0b prefix

>> 0b100
=> 4

OTHER TIPS

and you can do:

>> easy_to_read_binary = 0b1110_0000_0000_0000
=> 57344
>> easy_to_read_binary.to_s(10)
=> "57344"

For literals, the prefix is 0b. So

0b100 #=> 4

Be aware that the same exists to format strings:

"%b" % 4 #=> "100"

From this manual

0b01011

binary integer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top