Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a binary literal in ruby?

Tags:

ruby

binary

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?

like image 824
Thiago Arrais Avatar asked Sep 19 '08 12:09

Thiago Arrais


2 Answers

use 0b prefix

>> 0b100
=> 4
like image 143
Purfideas Avatar answered Jan 18 '23 07:01

Purfideas


and you can do:

>> easy_to_read_binary = 0b1110_0000_0000_0000
=> 57344
>> easy_to_read_binary.to_s(10)
=> "57344"
like image 33
Rob Avatar answered Jan 18 '23 05:01

Rob