# Thread: Good bitshifting tutorial or examples?

1. ## Good bitshifting tutorial or examples?

I need to take an array of characters (8 total) and output each character as its binary number using bit shifting. The idea is to print out an 8x8 grid using a single character for each row. I read in the "level.dat" file, which looks like this:

Code:
```00010010
11101110
01010010
01000010
11111011
00110010
01100010
01000010```
Using a function that the teacher provided:
Code:
```void Board::readBoard(const char *filename)
{
ifstream input;
char word[9];
input.open(filename);
for (int i = 0; i < BOARD_SIZE; i++)
{
input >> word;
for (int j = 0; j < 8; j++)
{
board[i] |= word[j] & 0x01;
if (j != 7)
{
board[i] <<= 1;
}
}
}
input.close();
}```
Once the file is read in, if I output board[] directly, it looks like this:
Code:
```↕
ε
R
B
√
2
b
B```
This is what I'm using to print the board onto the screen, but its coming out backwards:
Code:
```    // Prints all 8 rows backwards, argh!
for (int i = 0; i < 8; i++)
{
string bit = "";

for (int j = 0; j < 8; j++)
{
if((board[i] & 1 ) == 0)
bit += '0';
else
bit += '1';

board[i] >>= 1;
}

cout << i << line << bit << endl;
}```
I've spent about 5 hrs on Google, coding, trying things out and can't get anything to really work. In this case I'm just building a string and outputting it, I'm not really doing anything worth while. My next step after I get the "level" to display is to do bitwise operations on the rows and columns to make a game that you use to blank out all the 1's to 0's.

It almost feels like I should make another function that returns the binary number a given value and then loop through that so I can do comparisons in my other functions. Sort of just thinking out loud now. Anyone have any advice, or know of any good pages that talk about bit shifting or how to take a char to a binary number using bits? This topic is super confusing and I'm having a heck of a time wrapping my head around bits!

2. Do you realy mean for the code that converts the board into a binary string to be destructive? (I mean the board ends up as zeroes)

There are many easy ways to correct this, if your only problem is that it comes out backwards. You can prepend onto the string instead, or you can move the bits in the other direction, testing the highest bit instead of the lowest. Have a go at either of those and post your updated code.

Nobody spends 5 hours on google searching for something, that's just ridiculous. If you want people to feel sorry for you, then at least be realistic.

3. Just so you know, you are printing it backwards (and destroying your board in the process). The MSB is printed first (because that's how we write it), but you are printing LSB first.