Documentation

bitshift

Shift bits specified number of places

Syntax

c = bitshift(a, k)

Description

c = bitshift(a, k)returns the value ofashifted bykbits. The inputfiobjectamay be a scalar value or a vector and can be any fixed-point numeric type. The outputfiobjectchas the same numeric type asa.kmust be a scalar value and a MATLAB®built-in numeric type.

TheOverflowActionproperty ofais obeyed, but theRoundingMethodis alwaysFloor. If obeying theRoundingMethodproperty ofais important, try using thepow2function.

When the overflow action isSaturatethe sign bit is always preserved. The sign bit is also preserved when the overflow action isWrap, andkis negative. When the overflow action isWrapandkis positive, the sign bit is not preserved.

  • Whenk是正的,0-valued位转移的right.

  • Whenkis negative, andais unsigned, or a signed and positivefiobject, 0-valued bits are shifted in on the left.

  • Whenkis negative andais a signed and negativefiobject, 1-valued bits are shifted in on the left.

Examples

This example highlights how changing theOverflowActionproperty of thefimathobject can change the results returned by thebitshiftfunction. Consider the following signed fixed-pointfiobject with a value of 3, word length 16, and fraction length 0:

a = fi(3,1,16,0);
By default, theOverflowAction fimathproperty isSaturate. Whenais shifted such that it overflows, it is saturated to the maximum possible value:
for k=0:16,b=bitshift(a,k);... disp([num2str(k,'%02d'),'. ',bin(b)]);end 00. 0000000000000011 01. 0000000000000110 02. 0000000000001100 03. 0000000000011000 04. 0000000000110000 05. 0000000001100000 06. 0000000011000000 07. 0000000110000000 08. 0000001100000000 09. 0000011000000000 10. 0000110000000000 11. 0001100000000000 12. 0011000000000000 13. 0110000000000000 14. 0111111111111111 15. 0111111111111111 16. 0111111111111111
Now changeOverflowActiontoWrap. In this case, most significant bits shift off the “top” ofauntil the value is zero:
a = fi(3,1,16,0,'OverflowAction','Wrap'); for k=0:16,b=bitshift(a,k);... disp([num2str(k,'%02d'),'. ',bin(b)]);end 00. 0000000000000011 01. 0000000000000110 02. 0000000000001100 03. 0000000000011000 04. 0000000000110000 05. 0000000001100000 06. 0000000011000000 07. 0000000110000000 08. 0000001100000000 09. 0000011000000000 10. 0000110000000000 11. 0001100000000000 12. 0011000000000000 13. 0110000000000000 14. 1100000000000000 15. 1000000000000000 16. 0000000000000000

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced before R2006a

Was this topic helpful?