Does bit shift depend on platform/implementation?

P

Philipp

Hello
On http://cplus.about.com/od/advancedtutorials/l/aa042203h.htm
I found an example of bitshifting (see below).
Q: Is the bitshifting dependant on platform specific things (like how
the number is represented in memory) or can one count on the usual
behaviour (eg "<< 1" multiplies by 2) on any platform?

Thanks Phil

-- code found on web site --
#include <iostream>
using namespace std;

int main()
{
unsigned short bvec = 1024;

for (int i = 0; i < 15; i++) {
cout << bvec << endl;
bvec = bvec >> 1;
}

return 0;
}
----

Results:
1024
512
256
128
64
32
16
8
4
2
1
0
0
0
0
 
V

Victor Bazarov

Philipp said:
On http://cplus.about.com/od/advancedtutorials/l/aa042203h.htm
I found an example of bitshifting (see below).
Q: Is the bitshifting dependant on platform specific things (like how
the number is represented in memory) or can one count on the usual
behaviour (eg "<< 1" multiplies by 2) on any platform?

Yes, the behaviuor is standard. Left shift by 1 multiplies by 2, and
so on. The only implementation-defined behaviour is for the right
shift of a negative value of a signed type.

Of course, shifting more positions than the bits in the left operand
(integral-promoted) has undefined behaviour, also shifting with the
right operand negative also has undefined behaviour.

V
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top