noob c programming question

Venix

Golden Member
Aug 22, 2002
1,084
3
81
Originally posted by: Apathetic
Originally posted by: bignateyk
So if "y" were equal to 2, the result would be 4?

The correct answer is hardware dependent. Here's a Wikipedia article about "Endianness"

Dave

This is incorrect. According to the standard:

[#4] The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1×2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

[#5] The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity, 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

So you can portably use << and >> to multiply and divide by powers of 2, respectively.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
$ uname
Darwin
$ sysctl hw.byteorder
hw.byteorder: 4321
$ cat bitshift.c
#include <stdio.h>
int main() { int y = 2; printf("%d\n", (1 << y)); return 0; }
$ gcc -o bitshift bitshift.c && ./bitshift
4
$ cat bitshift.c | ssh kamper.ca 'cat > bitshift.c; uname; sysctl hw.byteorder; gcc -o bitshift bitshift.c && ./bitshift'
OpenBSD
hw.byteorder=1234
4
$ # hooray for portability