MATLAB: How to perform bitwise operations on other data types besides unsigned integers in MATLAB

bit-wisebitandbitxordoubleint16int32int64int8MATLABsingleuint16uint32uint64uint8

Currently, bitwise operations such as BITSHIFT, BITOR, etc. only work on unsigned integers (e.g. uint8).
I would like to perform the operations on other types, such as signed integers (e.g. int8) or the floating-point types (e.g. double).

Best Answer

This enhancement has been incorporated in Release 2012b (R2012b). For previous product releases, read below for any possible workarounds:
The ability to perform bitwise operations on data types other than unsigned integers is not available in base MATLAB.
As a workaround, use the TYPECAST function to reinterpret the bits of a number of one datatype as an unsigned integer with the same number of bits, and then perform the bitwise operation. Finally, use TYPECAST to convert the result back to the original type. For example:
i1 = int8(-7)
u1 = typecast(i1, 'uint8')
u2 = bitshift(u1, 1)
i2 = typecast(u2, 'int8')