<< >> shift in Matlab?

11 views (last 30 days)
Bob Li
Bob Li on 14 Oct 2011
In C, bitwise shift can be done using '<<, >>, which are even combined with assignment operators into '<<=, >>=.
In Matlab, I found functions like bitshift, bitsll, bitsra, bitsrl
Which are far less convenient than '<< >> operators. Is there any better way to do shifting.

Accepted Answer

Jan
Jan on 14 Oct 2011
No. There is no better way in Matlab. There are no >>= or similar inplace operators. This is a principal limitation of Matlab's internal data management.
You can shift by multiplying powers of 2. This has been faster than BITSHIFT in old Matlab releases. But today BITSHIFT is more efficient.
  2 Comments
Walter Roberson
Walter Roberson on 14 Oct 2011
If you use the multiplication approach, be careful about value saturation. When you use an int or uint data type, MATLAB does not simply discard bits that would "fall off the end": instead when it detects that the value would be above the numeric maximum for the data type, it sets the result to the numeric maximum for the datatype.
uint8(129) * uint8(2) does not, for example, become 128*2 + 1*2 with the 128*2 discarded: the result would be uint8(255), the maximum uint8 value.
Bob Li
Bob Li on 15 Oct 2011
Walter,
This behavior is somewhat different from C. C truncates over/underflow, while MATLAB clamps. I just read them on the Programming Fundamentals.
Thanks for reminding.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!