Bit operations
Ok this has got me stumped. If I have a variable which is equal to 0x54 how do I split it so I have two variables one equal to 5 and one equal to 4? Also how would I join those two variables together again?
I think it is something to do with left shift and right shift operators. I can get the 5 by >> 4 but << 4 doesn''t give me 0x4 it gives me something like 0xFFFA5 or something.
http://users.50megs.com/crazyvasey/
Simply 0x54 & 0x0F.
EDIT: It's much simpler to convert it to binary number and then think it over.
-Jussi
Edited by - Selkrank on August 22, 2000 8:12:52 AM
EDIT: It's much simpler to convert it to binary number and then think it over.
-Jussi
Edited by - Selkrank on August 22, 2000 8:12:52 AM
CV: The reason you have 0xFF.. on the front of your variable is probably because you''re using signed values (chars, ints, whatever). If you bit-shift, and your variable is signed, C will perform what''s called "sign-extension". The reason for this has to do with the way computers store signed numbers. If you want info on that, read-up on "two''s-compliment" (a.k.a. 2''s compliment) number systems.
Anyway, here''s an example of what you want to do:
Anyway, here''s an example of what you want to do:
unsigned short num = 0x4321;// get each nibble (4 bits) into a separate variableunsigned char n0, n1, n2, n3;n0 = num & 0x000F;n1 = (num & 0x00F0) >> 4;n2 = (num & 0x0F00) >> 8;n3 = (num & 0xF000) >> 12;// recombine them into a new variable// PS: not masking these because I already masked them aboveunsigned short new_num;new_num = (n3 << 12) | (n2 << 8) | (n1 << 4) | n0;
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement