9 years, 4 months ago.

Arithmetic or Logical Shift in mbed

Hello,

Does anyone know if mbed uses an arithmetic or logical shift when using << or >> operators.

Thanks Kas

1 Answer

9 years, 4 months ago.

Arithmetic: http://www.keil.com/support/man/docs/armccref/armccref_Babhccdh.htm

Accepted Answer

"Right shifts on signed quantities are arithmetic.

For values of type int,

Shifts outside the range 0 to 127 are undefined."

Outside the range of 0 - 127, does that mean my integer value is undefined if I have a value < 0 or > 127 because that would not really help, it basicly means all shifting is logical... The spec for me atleast is very unclear in what the expected behaviour is.

After reading the spec a few more times and with someone else it appears the confusing part is the 127, once right shifted 31 times the number should be zero and therefore why would there be a case of shifting more than that or why it would not just keep placing Zeros for positive and Ones for negative numbers is unclear.

I will assume (rightly or wrongly) that all shifting is arithmetic as long as its kept within understandable bounts (0 - 31)

Kas

posted by Kasriel Lewis 21 Jul 2015

Easiest in general is to just try it out. It makes no sense to shift it 128 or more times, so that is not a problem. Shifting negative is probably not even possible since I assume an unsigned value is used for shifting.

You need to consider that this all needs to be implemented in the CPU: If for whatever reason in the current implementation, shifting 129 times is the same as shifting one time (129 minus 128), they could either fix it in hardware, which will cost extra gates and will make the processor a (tiny) bit more expensive and power hungry, or they can simply tell people not to be stupid and not shifting 200 times.

Actually I wouldn't be surprised if the compiler already prevents it, although not sure. But then you could still force the CPU to do it by programming it in assembly. And if you do it, then the end result is not defined.

posted by Erik - 21 Jul 2015

Hello Erik,

I did finally try it and test this and it is a real arithmetic shift, as for shifting 127 or 128 times I did not try that as I feel that is an unrealistic operation to do.

Thankfully Kas

posted by Kasriel Lewis 24 Jul 2015