I need to know how to work with bit-words in Ruby? I am reading a book
called “Chess Skill in Man and Machine” by James Frey in which he
describes doing logic-and and logic-or operations on bit-words like so:
01011100 logic-and
11010011 results in
01010000 (1’s appear in the result only where there was a 1 in both
bit-words).
01011100 logic-or
11010011 results in
11011111 (1’s appear in the result where there is a 1 in either
bit-words).
This is what I need to be able to do in Ruby.
I have tried using binary numbers, for example:
a = 0b01000100
puts a
68
But I don’t think binary numbers are the same as bit-words? I’m
basically just not sure where to start. Any help appreciated.
It makes perfect sense to interpret bit words as “binary numbers”
(binary representations of numbers). So your idea of writing
a = 0b01000100
is absolutely right. You have to note though, that Ruby prints out
numbers as decimal representations by default. If you want them to be
printed out as binary representations, you have to write
puts a.to_s(2)
This will display 1000100. To print out numbers with a fixed length and
pad them with zeros, you can use the Kernel method “printf”:
I assume you meant ‘sprintf’ not ‘printf’? I tried ‘printf’ and got
error messages.
I know I’m going to have to create a BitBoard class so that I can create
bitboard objects to go on the chess board. I assume I will be putting
the automatic conversion to binary in that.
sprintf (alias format) returns a formatted string, whereas printf
outputs a formatted string. printf(’%08b’, 0b1) is the same as
print(sprintf(’%08b’, 0b1)).
As to the conversion:
You don’t really have to “convert” the numbers for the bitboard or chess
board to work. All the calculation is done directly on integers and has
nothing to do with how these integers are represented. So instead of
writing 0b1100 & 0b1010, you might as well write 12 & 10, which is
exactly the same.
You’ll need the (s)printf only for displaying the board. So it’s
probably best to use it in the to_s method of the class:
class ChessBoard
…
def to_s
format …
end
…
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.