What is the value of (-1 >> 6)?

G

Grant

Are the bitwise operators >>, <<, &, |, ~, ^ only defined for
non-negative values?

The little program below produces the output
3 255
I expected to get the 3 but why does it produce the 255 when the
variable c is not typecast first?






#include <stdio.h>

int main(int argc, char **argv) {

char c = -1;
unsigned char uc1 = (unsigned char)c >> 6;
unsigned char uc2 = c >> 6;

printf("%hhu %hhu\n", uc1, uc2);
return 0;
}
 
T

Tim Prince

Grant said:
Are the bitwise operators >>, <<, &, |, ~, ^ only defined for
non-negative values?

The little program below produces the output
3 255
I expected to get the 3 but why does it produce the 255 when the
variable c is not typecast first?






#include <stdio.h>

int main(int argc, char **argv) {

char c = -1;
unsigned char uc1 = (unsigned char)c >> 6;
unsigned char uc2 = c >> 6;

printf("%hhu %hhu\n", uc1, uc2);
return 0;
}
When you don't specify whether you want signed or unsigned char, you leave
it up to the designers of your compiler. Apparently, you tested on a
system where it's signed 2's complement.
 
P

pete

Jack said:
NO!

They are only well-defined. Their effects when right shifting signed
types is implementation-defined, but that is a far cry from undefined.

"undefined aspects" is undefined, enough for me.

N869
6.5 Expressions
[#4]
... bitwise operators ...
These operators return values that depend on the internal
representations of integers, and have implementation-defined
and undefined aspects for signed types.
 
P

pete

right shift *is* implementation defined,
but OP asked about bitwise operators as a group,
so I took my answer from the part of the standard
which addresses the issue for bitwise operators
as a group.
"undefined aspects" is undefined, enough for me.

N869
6.5 Expressions
[#4]
... bitwise operators ...
These operators return values that depend on the internal
representations of integers, and have implementation-defined
and undefined aspects for signed types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,218
Latest member
GracieDebo

Latest Threads

Top