I am trying to read a bitmap file header (I know that windows API can do this)
But I am trying to read the file directly. I know how it is formated.
I read the first two bytes okay and have no problem converting them into the string "BM". Then I try to read the next 4 bytes which should give me a long int or unsigned long int.
I use fgets() to dump the 4 chars into a chars array of size [4]
but how do I convert this string of 4 characters into an integer representing an unsigned long int.
(I used ftell so I am sure I am reading the correct number of bytes.)
To be specific how do I read an unsigned long from a binary file?
Use an array of 4 unsigned chars. If you use signed chars you may have problems of sign extension.
1 2 3 4 5
unsignedlong n=0
for (int i=3;i>=0;i--){
n<<=8;
n|=array[i];
}
This assumes that the integer is stored in little endian, which I'm pretty sure that's how BMP stores them. If I'm wrong, you'll have to invert the order.
Right now I am trying to turn the 4 unsigned chars into one long int.
Is there an easy way to do that, or a hard way?
Also I just tried typecasting my char[4] to an unsigned long int.
But then I get a result of 4343960 for an integer which should be 4807.
The integer should represent a file size so I know the result I should be getting.
<< and >> are shift operators. They are used to shift the bits of an integers. In a nutshell, shifting to left (<<) by 1 is like multiplying by 2, and shifting to the right by 1 is like dividing by 2.
What I did there is multiply n by 256 (2^8=256). Using shifts, however, is faster.
| is the bitwise OR. It's used to set bits.
Compounded, what the two lines do is this:
n=00 00 F4 78
n<<=8
n=00 F4 78 00
n|=AA
n=00 F4 78 AA
Okay I understand most of it now, I see how the bitwise OR works but how does the bitwise OR get the final result by comparing bits? Sorry if it is obvious, I am just not seeing it.
It doesn't compare bits (in fact, not even boolean OR does, so I can't help but wonder where you got that idea).
Suppose we want to OR 225 with 45: v
1110 0001 //225
0010 1101 //45
1 OR 1 = 1
0000 0001 //result
v
1110 0001
0010 1101
0 OR 0 = 0
000000001
v
1110 0001
0010 1101
0 OR 1 = 1
000000101
v
1110 0001
0010 1101
0 OR 1 = 1
0000 1101
...
v
1110 0001
0010 1101
1 OR 0 = 1
1110 1101
That's what bitwise OR does.
Now imagine what happens if you do 0|AB. This is how you push bytes into an integer.
Then imagine what happens if you do 0|8. This is how bit flags are set (they are reset with AND).
Oh I am really getting it now...just about there. I was confused because I had never seen that syntax before.
<<=8
and n|=array
are similar to n+=1
same type of short hand.
I thought it was a special thing or something.
Sorry for using the word 'compare' I guess it is not really accurate.
I can kinda see how you can create a set of bits now. I think this needs some more brain work on my part.