Posted By: txesmi
confused with bits - 05/27/18 09:41
Hi!
If someone shows me these two fuctions I will state, without a doubt, that both output the same string. Both print bit by bit, from left to right, the four bytes of an integer, aren't they? They do not
Value:
65536 + 128 + 2 + 1
First function output:
00000000 00000001 00000000 10000011 -> as spected
Second function output:
10000011 00000000 00000001 00000000 -> WTF? The bytes are printed fine but in reverse order!
I am so sure the function is right that I got locked by my own selfconviction. Don't get me wrong, I know how to reverse the loop. The problem is that it goes against all I know about what the memory is so I need to know what is going on. I can't understand. Did I get blind?
Any idea would be apreciated. Thanks in advance.
Code:
void intDrawBits (int _i, int _posX, int _posY) { if (_i & (1 << 31)) // avoid arithmetic bitwise draw_text("1", _posX+=12, _posY, COLOR_WHITE); else draw_text("0", _posX+=12, _posY, COLOR_WHITE); int _bit = 1 << 30; for (; _bit>0; _bit=_bit>>1) { if (_i & _bit) draw_text("1", _posX+=12, _posY, COLOR_WHITE); else draw_text("0", _posX+=12, _posY, COLOR_WHITE); } } void intDrawBitsByBytes (int _i, int _posX, int _posY) { BYTE *_b = (BYTE*)&_i; BYTE *_bLast = _b + sizeof(int); for (; _b<_bLast; _b+=1) { BYTE _bit = 1 << 7; for (; _bit>0; _bit=_bit>>1) { if (*_b & _bit) draw_text("1", _posX+=12, _posY, COLOR_WHITE); else draw_text("0", _posX+=12, _posY, COLOR_WHITE); } } }
If someone shows me these two fuctions I will state, without a doubt, that both output the same string. Both print bit by bit, from left to right, the four bytes of an integer, aren't they? They do not
Value:
65536 + 128 + 2 + 1
First function output:
00000000 00000001 00000000 10000011 -> as spected
Second function output:
10000011 00000000 00000001 00000000 -> WTF? The bytes are printed fine but in reverse order!
I am so sure the function is right that I got locked by my own selfconviction. Don't get me wrong, I know how to reverse the loop. The problem is that it goes against all I know about what the memory is so I need to know what is going on. I can't understand. Did I get blind?
Any idea would be apreciated. Thanks in advance.