tags:

views:

853

answers:

4

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?

+2  A: 

From http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#numeric">http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#numeric

0b01011

binary integer

Thelema
+8  A: 

use 0b prefix

>> 0b100
=> 4
Purfideas
+2  A: 

For literals, the prefix is 0b. So

0b100 #=> 4

Be aware that the same exists to format strings:

"%b" % 4 #=> "100"
webmat
+3  A: 

and you can do:

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