1. long int temp;
2. int product = -1;
3. temp = (long int)product & 0xFFFFFFFF;
4. temp = temp << 32;
I know that temp is 64-bit while product is 32-bit.
I am slightly confused about lines 3 and 4.
We are casting product as a long int, which means product should get represented as 64-bit and doing a bitwise AND with 0xFFFFFFFF. The hexadecimal representation of 0xFFFFFFFF is all 1's, so the AND should preserve the binary representation of -1?
Since -1 in binary is 1111111111111111, would temp now be 32 1's followed by 32 0's, or vice versa? If the former, is there any point to doing the left shift on line 4?
I am mainly confused about the conversion of 32-bit to 64-bit here and how it looks in binary.
On line 3, the following happens:
Since the type cast operator has higher operator precedence than the & operator, the program first converts the 32-bit respresentation of the number -1 in the variable product to a temporary 64-bit representation of the number -1. It does this by sign extending the upper 32 bits. Since the sign bit has the number 1, the upper 32 bits will be filled with 1s, so that the temporary 64-bit value now consists of 64 1s. Now, that temporary value is ANDed with 0xFFFFFFFF, which keeps the lower 32 bits intact and zeroes the upper 32 bits. So, now the temporary value has the value 0x00000000FFFFFFFF, which no longer corresponds to -1, because the value is now positive, since the sign bit (the highest bit) is now set to zero. This temporary value has the value 4,294,967,295 in decimal. It is now assigned to the variable temp.
On line 4, the following happens:
The value in the variable temp, which is 0x00000000FFFFFFFF, is now left shifted by 32 bits, to the value 0xFFFFFFFF00000000. This new value is now assigned to temp. Since the sign bit (the highest bit) is now set to 1 again, the value is negative, but it is no longer -1. Its value now is -4,294,967,296 in decimal representation. See this Wikipedia article for more information on how negative numbers are represented in binary.
Related
There is a 2 byte packet. The first 5 bits represent the version, the next 5 bits represent the type, and the last 6 bits represent the value. I am passing the packet as a char* to a function (print_pak). In that function, I want to print the version, type, and packet value. How can I do that?
void print_pak(char* pak)
{
}
You need to use bit masking and shifting for this. Also, when doing bit manipulation, I believe it's preferred to work with unsigned integer types since the binary representation of negative integers is not defined by the C standard.
void
print_pak(const unsigned char *pak)
{
unsigned char version, type, value;
version = (pak[0] >> 3);
type = ((pak[0]&0x07) << 2) + (pak[1] >> 6);
value = pak[1]&0x3f;
printf("Version = %u, Type = %u, Value = %u\n", version, type, value);
}
Here's how this works. The << and >> operators are for bit shifting. Suppose you have an unsigned char, x, which holds the bits 10111010. Shifting it right by 3 bits is done by (x >> 3) (operator precedence always trips me up when doing bit manipulation so I throw in parentheses to be safe). The right three bits can't go anywhere and so they fall off. The result is 00010111. Shifting to the left works the same (sort of).
Bit masking, &, implements binary "and". That is, if x is 10101011 and y is 00011111, then x&y only has 1's where x and y share them. So, it would be 00001011.
Let's take all of this and tackle your problem. The version is the first five bits of the first byte. Therefore, we want to right shift the low three bits off.
The type is the last three bits of the first byte followed by the first two bits of the second byte. That first group can be acquired by masking off the high five bits of the first byte (0x07 is 00000111 in binary). The second group can be acquired by right shifting the second byte by six bits. Then, to put them together, you need to left shift the first group by two bits to make room for the second group.
Finally, the value is the low six bits of the second byte which can be acquired by a simple masking of those bits (0x3f is 00111111 in binary).
Assignment operators are not something I expected to struggle with. Everything in this section so far is familiar, but the way they explain it makes it seem foreign. I think it's the bitwise operators I'm confused about.
Anyway here is the part I don't get.
The function bitcount counts the number of 1-bits in its integer argument.
/*bitcount: count 1 bits in x */
int bitcount (unsigned x)
{
int b;
for(b=0; x != 0; x >>= 1) {
if(x & 01)
b++;
return b;
}
Declaring the argument x to be unsigned ensures that when it is right-shifted, vacated bits will be filled with zeros, not sign bits, regardless of the machine the program is run on.
Not that I really understand the code, but this last sentence is confusing me the most. What does this mean? Does it mean "ones" by "sign bits" and does this have to do with twos complement?
I really had trouble getting through the bitwise operations. Can anyone recommend some comprehensive material to supplement the bitwise stuff in this book?
Suppose x is two’s complement. For illustration, let‘s use an eight-bit width. (C always shifts in a wider width, at least that of int.)
If x is 64 (010000002) and we shift it right one bit, we get 32 (001000002). When we repeat that, we get 16 (000100002), 8 (000010002), 4 (000001002), 2 (000000102) , and 1 (000000012).
When x is −64, two’s complement represents it with 110000002. If we shift that right and bring in a 0 bit, the bits are 011000002, which represents 64+32 = 96. So −64 becomes 96. Now, that might be fine if one were just working with bits. But, if we want to use bit-shifting to divide numbers, we want −32, not 96. The bits for −32 are 111000002. So we can get that by bring in a 1 bit instead of a 0 bit. And the bits for −16 are 111100002. Then −8, −4, −2, and −1 are 111110002, 111111002, 111111102, 111111112. In each case, we bring in a 1 bit when shifting.
So, if we want to use bit-shifting for division, there is a simple rule for a one-bit shift: Shift all bits right one spot and leave the sign bit as is (0 or 1). If we are shifting more than one bit, keep copying the sign bit.
That is called an arithmetic right shift. So, we have two kinds of right shift: An arithmetic right shift that copies the sign bit, and a logical right shift that brings in 0 bits.
For unsigned types, the C standard says a right shift is logical.
For signed types, the C standard does not say whether it is arithmetic or logical. It leaves it to the implementation to define which that implementation uses (or possibly to define something else). That might be due to the history; early machines might not have provided arithmetic right-shift instructions (and may not even have used two’s complement), although it seems hard to imagine these days.
So, when you are writing code that shifts right and you want to be sure of the result you will get, you can use an unsigned type to be sure to get a logical shift.
In twos complement representation the highest order bit is reserved for the sign. The highest order bit is 0 for positive numbers and 1 for negative numbers.
If you right shift the bits of a negative number the 1 originally in the highest order bit will be shifted to the next lower order bit, eventually ending up in the lowest order bit if you keep shifting the bits.
In the code the for loop shifts the bits of x by one bit position and assigns the shifted value to x.
for (b = 0; x != 0; x >>=1 )
First b, which is used to count the number of 1 bits in the number is set to 0.
The condition to continue the loop is x != 0. When all the 1 bits are shifted out of x the only thing left will be 0 bits. x will then equal 0.
The operation performed after each iteration is to right-shift the value in x by 1.
The if condition in the body of the loop performs bit-wise AND operation on x. The bit mask has a value of 1, which is an instance of the int value with all bits 0 except the lowest order bit. That AND operation will evaluate to 1 (or true in C) if the lowest order bit is 1, and to 0 (or false in C) if the lowest order bit is 0. The count of one bits is incremented if the if condition is true.
In memory 128 will be stored as 10000000. Where should I place the sign bit here since whole 1 byte is occupied by number 128 if i store -128 in byte datatype?
Can you please explain me?
Signed integers are typically represented in two's complement. This means that for a given positive number, the corresponding negative number is obtained by inverting all bits then adding 1.
A negative number in two's complement will have the high order bit set. This bit becomes the sign bit.
So for a number occupying a single byte, 11111111 represents -1, 11111110 represents -2, and so forth, all the way to 10000000 which represents -128. On the high end, 01111111 represents 127.
This means that a 1 byte signed integer cannot store the value 128. If you had a 1 byte unsigned integer then 10000000 would be 128 but then it could not hold any negative numbers.
A single byte means 8 bits, which mean you can choose from 2^8 = 256 values. In C representation for signed char (or signed integer of 1 byte) teh values chosen were from [-128, 127] including both extremes
you could cast to unsigned char, like
char s128 = (char)128;
if((unsigned char)s128==128){
printf("true\n");
}
I have a card game where I need to display the value of the card after I shuffle I display the value of the card using values (x >> 1)& 0xf where x iterates through the list of 13 cards this is found as bit 1-4 is the value of the card
the above is card type
But when I come across finding the highest pair in the card it only works when I use values[(afterfindingpairs[a]&0xf0)>>4].
This is worked out as 0-4 bits are the no of pairs whereas the 4-7 bits are the values of the pair in the byte of pair type.
It just displays the highest pair as Ace when I use
values[(afterfindingpairs[a]&0xf)>>4].
I'm confused wouldnt the hexadecimal 0xf0 deal with 8 bits rather than the 4 bit between 4-7 of the pair type which would be found by values[(afterfindingpairs[a]&0xf)>>4] which is incorrect.
Explanation as to why this happens would be much appreciated.
You appear to want to manipulate 8-bit values, extracting various ranges of bits. However in some cases you're doing so in such a way as to discard all the bits.
The 8 bits are arranged from least significant (bit 0, which is '1' in decimal), to the most significant (bit 7, which is '128' in decimal).
So if we had the binary number 10010110, this would represent the number (128 + 16 + 4 + 2), or 150, or 0x96 in hex.
If you apply a right-shift to such a number, the bits will be moved to the right by the appropriate number of places. So if we did >>4 to the number above, the result will be 00001001 - or 9. I have assumed we are dealing with unsigned values here, so the upper bits will be filled in with '0'. Note that the result is that the original bits 4-7 are now bits 0-3, and the original bits 0-3 have been discarded.
If you and two numbers, the result is that only bits which are set in both will be set in the result. So effectively this is masking bits. If you mask with 0xf0, this is in binary 11110000, so only the upper bits, 4-7 will remain in the result, and the lower bits 0-3 will be set to zero.
Take your statement:
values[(afterfindingpairs[a]&0xf0)>>4]
The expression afterfindingpairs[a]&0xf0, as per my explanation above, will simply set bits 0-3 to zero, retaining bits 4-7.
The next part of the expression, >>4 will shift those remaining bits down so they become bits 0-3 of the result. Note that this also discards the original bits 0-3, making the previous mask operation redundant (unless we are not dealing with 8-bit values...)
Your other statement:
values[(afterfindingpairs[a]&0xf)>>4]
Is more problematic. You first apply a mask (0xf) retains only bits 0-3, setting all others to zero. Then you apply a shift which throws away bits 0-3, by shifting bits 4-7 (which are already zero) down into their place.
In other words, this latter expression is always zero.
This is a doubt regarding the representation of bits of signed integers. For example, when you want to represent -1, it is equivalent to 2's complement of (+1). So -1 is represented as 0xFFFFFFF. Now when I shift my number by 31 and print the result it is coming back as -1.
signed int a = -1;
printf(("The number is %d ",(a>>31));//this prints as -1
So can anyone please explain to me how the bits are represented for negative numbers?
Thanks.
When the top bit is zero, the number is positive. When it's 1, the number is negative.
Negative numbers shifted right keep shifting a "1" in as the topmost bit to keep the number negative. That's why you're getting that answer.
For more about two's complement, see this Stackoverflow question.
#Stobor points out that some C implementations could shift 0 into the high bit instead of 1. [Verified in Wikipedia.] In Java it's dependably an arithmetic shift.
But the output given by the questioner shows that his compiler is doing an arithmetic shift.
The C standard leaves it undefined whether the right shift of a negative (necessarily signed) integer shifts zeroes (logical shift right) or sign bits (arithmetic shift right) into the most significant bit. It is up to the implementation to choose.
Consequently, portable code ensures that it does not perform right shifts on negative numbers. Either it converts the value to the corresponding unsigned value before shifting (which is guaranteed to use a logical shift right, putting zeroes into the vacated bits), or it ensures that the value is positive, or it tolerates the variation in the output.
This is an arithmetic shift operation which preserves the sign bit and shifts the mantissa part of a signed number.
cheers
Basically there are two types of right shift. An unsigned right shift and a signed right shift. An unsigned right shift will shift the bits to the right, causing the least significant bit to be lost, and the most significant bit to be replaced with a 0. With a signed right shift, the bits are shifted to the right, causing the least significant bit be be lost, and the most significant bit to be preserved. A signed right shift divides the number by a power of two (corresponding to the number of places shifted), whereas an unsigned shift is a logical shifting operation.
The ">>" operator performs an unsigned right shift when the data type on which it operates is unsigned, and it performs a signed right shift when the data type on which it operates is signed. So, what you need to do is cast the object to an unsigned integer type before performing the bit manipulation to get the desired result.
Have a look at two's complement description. It should help.
EDIT: When the below was written, the code in the question was written as:
unsigned int a = -1;
printf(("The number is %d ",(a>>31));//this prints as -1
If unsigned int is at least 32 bits wide, then your compiler isn't really allowed to produce -1 as the output of that (with the small caveat that you should be casting the unsigned value to int before you pass it to printf).
Because a is an unsigned int, assigning -1 to it must give it the value of UINT_MAX (as the smallest non-negative value congruent to -1 modulo UINT_MAX+1). As long as unsigned int has at least 32 bits on your platform, the result of shifting that unsigned quantity right by 31 will be UINT_MAX divided by 2^31, which has to fit within int. (If unsigned int is 31 bits or shorter, it can produce whatever it likes because the result of the shift is unspecified).