Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this syntax for defining binary numbers in ruby?

Tags:

ruby

binary

some terminal output is worth a thousand words so lets start with that:

[10] pry(main)> 1_000
=> 1000

yep, we can define thousands in a readable way in ruby, I know that and everythings fine. Hey, I wonder what would happen if I try and left pad that with zeroes?

[9] pry(main)> 001_000
=> 512

Well that's weird, it's not binary as that would be 8 hmm...

[20] pry(main)> 01_0
=> 8

so that's 8... ok, 2**3 is 8, 2**(3*3) is 512 I bet 01_00 is 2**6==64

[24] pry(main)> 01_00
=> 64

hmm... there's nothing special about the underscore in the number syntax, it's just to make it look nice:

[23] pry(main)> 0100
=> 64

So what are these numbers called (it's not straight binary... I'm trying to think of what they should be but keep coming up with a blank). In addition why are they so important? could anyone post a link to the documentation describing them?

like image 299
Mike H-R Avatar asked Jan 10 '23 15:01

Mike H-R


1 Answers

If numbers are prefixed with 0, it's octal representation.

Similarly, if numbers are prefixed with 0x or 0X, it's hexadecimal reprepsentation.

0x10
# => 16
0x100
# => 256

BTW, You can convert numbers to octal, hexadecimal, binary representation using % operator or sprintf:

'%o' % 512
=> "1000"

'%x' % 256
# => "100"

'%x' % 512
# => "200"

'%b' % 3
# => "11"
like image 65
falsetru Avatar answered Jan 18 '23 14:01

falsetru