Bit arithmetic in C

VanGo

Say we have 11101111 stored in the address address, how would I add the first 4 bits to the last 4 bits?

My prof showed us we can do this (*address)/16 + (*address)%16 but I don't understand why it works. Can someone explain where the division and modulo with 16 come from?

Sumit Gemini

@VanGo, See to perform operation on bits, you have to learn bitwise operator first.

I am explaining your problem here.

11101111 (is in binary form) and is equivalent to 239 (in decimal). Now you have to add 1110 in 1111. In order to get these two pair of 4 bits from 11101111, you have to perform bitwise operation on 11101111.

To get higher 4 bits, shift 11101111 four times from left to right.

*address >> 4 :- is equal to *address/16

internally compiler convert *address>>4 into (*address)/(2 pow 4).

To get lower 4 bits, either perform (*address)&0x0f or (*address)%16. Both operation will clear all bits except lower 4 bits.

    printf(".....%d\n",(((*address)>>4) + ((*address)&0x0f)));

hope it helps you.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related