Here is a simple way of getting two's complement: action So, the two's complement satisfies basic arithmetic, but one's complement (The resulting number by changing just the sign bit) does not. In other words, the bit pattern for -(x+1) can be described as the complement of the bits in x(aka ~x). To get negative representation of any integer, take bitwise complement and then add one! ~x + 1 = -x The resulting number is the two's complement of the number. Invert a bit pattern of a number, and then add 1. Then, how we make the sum of the two be zero?īy adding 1 after inverting all the bits in 00000111 (7): So, we need to change it to the system like the picture below: We have two issues: (two 0s and (+1)+(-1) is not zero). Let's look at the diagram for 4-bit number system: However, when we do an addition of the two, it does not become 0: Then, -7 will have the following bit pattern: How about -7? If we use the Most Significant Bit (MSB) as a sign bit, and let the value of 1 represent (-) sign. The number 7 is expressed by the following bit pattern: Let's limit our discussion to 8 bits (1 byte). In computer, every bit is mapped representing something. The code below shows how to set or clear a bit of an integer. #define CLEARBIT(a, pos) (a &= ~(1 >8) & 0xff // left most (most significant) byteĪssuming 16 bit, 2-byte short integer, two's complement: Note that a bitwise right-shift will be the equivalent of integer division by 2:ġst arg: int, 2nd arg: bit position to clear */ >): Moving all the bits of a number a specified number of places to the right. X^y = (x|y) & !(x&y ) : either x or y but not both Bit n of ~x is the opposite of bit n of xīit n of x&y is 1 if bit n of x and bit n of y is 1.īit n of x|y is 1 if bit n of x or bit n of y is 1.īit n of x^y is 1 if bit n of x or bit n of y is 1 but not if both are 1.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |