Brian Ambielli
Brian Ambielli

Reputation: 601

Convert int to binary, the perform bitwise operations on it

I'm trying to convert an int to binary, and then perform bitwise operations on the binary.

My current method is to take the int, call to_s(2) on it, but then I'm left with a binary string.

Any advice on what I should do?

Upvotes: 0

Views: 2509

Answers (2)

Jingkai He
Jingkai He

Reputation: 24

the_number.to_s(2).split('').map { |x| x.to_i } # convert the number to binary array

Upvotes: 0

nneonneo
nneonneo

Reputation: 179392

Simple integers are stored as binary in nearly every major programming language (including Ruby). So, you can do your bitwise operations on the integers themselves:

>> 6 | 5 # bitwise or
=> 7
>> 6 & 5 # bitwise and
=> 4
>> 6 ^ 5 # bitwise xor
=> 3
>> 6 >> 2 # right shift
=> 1
>> 6 << 2 # left shift
=> 24

(Edit: this appears to be my 1000th answer.)

Upvotes: 6

Related Questions