confused with bits

Posted By: txesmi

confused with bits - 05/27/18 09:41

Hi!

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 confused

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.
Posted By: Quad

Re: confused with bits - 05/28/18 10:41

It has to with endianness:
https://stackoverflow.com/questions/6018386/so-on-x86-64-its-big-endian/41380488#41380488

second answer on this link explains it.
Posted By: txesmi

Re: confused with bits - 05/28/18 12:22

Thank you very much for pointing me out! So it works as it is. It explains more things. I never heard about it blush

Indeed, the reason I run over this issue is a module I am working on that let me operate with integers of undefined lenght and I sorted the bytes the same manner laugh
© 2024 lite-C Forums