TExcelTAD
Home › MATLAB / Octave › Integers & Bitwise Operations

Integers & Bitwise Operations

Most MATLAB code never leaves double. Integer types matter when you talk to hardware, read binary files, process images, pack flags into a single number or need whole numbers beyond 2^53. Data Types & Classes introduced the integer classes, their rounding and their saturation. This lesson goes further: ranges and precision, mixing rules, and the functions that work on individual bits. Everything here runs in both MATLAB and Octave.

The integer classes

Class Bits Range Typical use
int8 / uint8 8 -128 … 127 / 0 … 255 Image pixels, bytes of a file
int16 / uint16 16 -32 768 … 32 767 / 0 … 65 535 Audio samples, sensor readings
int32 / uint32 32 about ±2.1 × 10^9 / 0 … 4.29 × 10^9 Counters, IDs, packed colours
int64 / uint64 64 about ±9.2 × 10^18 / 0 … 1.8 × 10^19 Timestamps in ns, large IDs

intmin and intmax give the exact limits, and class(x) or isinteger(x) tell you what you have:

matlab · try it yourself
types = {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32'};
for k = 1:numel(types)
    fprintf('%-7s %12d %12d\n', types{k}, intmin(types{k}), intmax(types{k}));
end
disp(intmax('int64'))
disp(isinteger(int16(5)))
disp(isinteger(5))
int8            -128          127
uint8              0          255
int16         -32768        32767
uint16             0        65535
int32    -2147483648   2147483647
uint32             0   4294967295
9223372036854775807
1
0

Note that isinteger(5) is false: the value 5 is whole, but its class is double.

Conversion: rounding and clamping

Converting to an integer class rounds to the nearest integer (halves away from zero) and clamps values that don't fit. NaN becomes 0:

matlab · try it yourself
disp(int16([2.5 -2.5 3.49 1e6 -1e6]))
disp(uint8([-5 NaN Inf 300]))
x = uint8(200);
disp(x + 100)
disp(x - 250)
disp(abs(uint8(3) - uint8(5)))
disp(abs(double(uint8(3)) - double(uint8(5))))
       3      -3       3   32767  -32768
    0    0  255  255
255
0
0
2

The last two lines show a classic image-processing bug: the difference of two uint8 pixels is clamped to 0 before abs sees it. Convert to double (or a wider signed type) before subtracting.

Division rounds too, and dividing a non-zero integer by zero saturates instead of giving Inf:

matlab · try it yourself
disp(int32(7) / int32(2))
disp(idivide(int32(7), int32(2)))
disp(idivide(int32(7), int32(2), 'floor'))
disp(idivide(int32(-7), int32(2), 'floor'))
disp(int8(5) / int8(0))
disp(int8(-5) / int8(0))
disp(mod(int16(-7), 3))
4
3
3
-4
127
-128
2

idivide truncates toward zero by default ('fix'); 'floor', 'ceil' and 'round' choose other rounding.

Mixing types

Expression Result class
integer op double the integer class (computed, then rounded back)
integer op logical / char the integer class
int8 op int16 (two different integer classes) error
single op double single
matlab · try it yourself
a = uint8(10);
disp(class(a * 2.6))
disp(a * 2.6)
disp(class(a + true))
try
    b = int8(1) + int16(1);
catch
    disp('int8 + int16 is an error; convert first:')
    disp(class(int16(int8(1)) + int16(1)))
end
uint8
26
uint8
int8 + int16 is an error; convert first:
int16

The exact error message differs between MATLAB and Octave, so the example prints its own text. To combine two integer classes, convert one explicitly, usually to the wider type.

Beyond 2^53: when int64 matters

A double stores integers exactly only up to flintmax = 2^53 (about 9 × 10^15). Beyond that, neighbouring integers have the same representation. int64 and uint64 keep every digit:

matlab · try it yourself
big = 2^53;
fprintf('flintmax: %d\n', flintmax);
disp(big + 1 == big)
n = int64(2)^53;
disp(n + int64(1))
disp(n + int64(1) == n)
id = intmax('uint64') - uint64(5);
disp(id)
flintmax: 9007199254740992
1
9007199254740993
0
18446744073709551610

In double precision 2^53 + 1 rounds back to 2^53, while the int64 sum is exact. Be careful when typing big literals: int64(9007199254740993) first creates the double 9007199254740993, which MATLAB rounds to ...992 before converting (Octave 11 happens to read such integer literals exactly, so the two disagree). Build big values from smaller integer pieces, as above, or parse them from text.

Bitwise functions

The bit* functions treat a number as a pattern of binary digits. They accept unsigned integers and non-negative whole double values:

Function Result bit is 1 when…
bitand(a, b) both bits are 1
bitor(a, b) at least one bit is 1
bitxor(a, b) the bits differ
bitcmp(a) the bit is 0 (all bits flipped, within the class width)
bitshift(a, n) shifts left by n (right for negative n)
bitget(a, k) / bitset(a, k, v) reads / sets bit k (bit 1 is the least significant)
matlab · try it yourself
a = 12;  b = 10;
fprintf('a = %s, b = %s\n', dec2bin(a, 4), dec2bin(b, 4));
fprintf('and %s = %d\n', dec2bin(bitand(a, b), 4), bitand(a, b));
fprintf('or  %s = %d\n', dec2bin(bitor(a, b), 4), bitor(a, b));
fprintf('xor %s = %d\n', dec2bin(bitxor(a, b), 4), bitxor(a, b));
disp(bitcmp(uint8(5)))
disp(bitshift(1, 0:4))
disp(bitshift(160, -3))
disp(bitshift(uint8(200), 1))
a = 1100, b = 1010
and 1000 = 8
or  1110 = 14
xor 0110 = 6
250
    1    2    4    8   16
20
144

Shifting left by n multiplies by 2^n and shifting right divides by 2^n (dropping the remainder). With a fixed-width type the bits pushed out on the left are lost, so bitshift(uint8(200), 1) is 144 (400 - 256), not the saturated 255 that uint8(200) * 2 gives.

Flags in a single number

A classic use of bits is to store several yes/no options in one integer, each option owning one bit. File permissions work this way:

matlab · try it yourself
READ = 1;  WRITE = 2;  EXEC = 4;
perm = bitor(READ, WRITE);
fprintf('perm = %d (%s)\n', perm, dec2bin(perm, 3));
fprintf('can write: %d, can execute: %d\n', bitand(perm, WRITE) > 0, bitand(perm, EXEC) > 0);
perm = bitor(perm, EXEC);
perm = bitand(perm, bitcmp(uint8(WRITE)));
fprintf('after adding EXEC and removing WRITE: %d (%s)\n', perm, dec2bin(perm, 3));
bits = bitget(uint8(perm), 1:3)
perm = 3 (011)
can write: 1, can execute: 0
after adding EXEC and removing WRITE: 5 (101)
bits =

  1  0  1

bitor sets a flag, bitand with the flag tests it, and bitand with the complement clears it. bitget returns all bits at once, least significant first.

Binary and hexadecimal text

Function Converts
dec2bin(n, digits) / bin2dec(s) Number ↔ binary text
dec2hex(n, digits) / hex2dec(s) Number ↔ hexadecimal text
dec2base(n, b) / base2dec(s, b) Any base from 2 to 36
matlab · try it yourself
disp(dec2bin(10))
disp(dec2bin(10, 8))
disp(bin2dec('11111111'))
disp(dec2hex(48879))
disp(hex2dec('FF'))
disp(dec2base(255, 3))
codes = dec2bin([1 5 10])
1010
00001010
255
BEEF
255
100110
codes =

0001
0101
1010

For a vector, dec2bin returns a char matrix with one row per number, padded to the same width.

Packing values: an RGB colour

Shifts and masks pack several small numbers into one bigger one. A 24-bit colour holds red, green and blue bytes:

matlab · try it yourself
r = uint32(255);  g = uint32(136);  b = uint32(0);
color = bitor(bitor(bitshift(r, 16), bitshift(g, 8)), b);
fprintf('packed: %d = #%s\n', color, dec2hex(color, 6));
red   = bitand(bitshift(color, -16), uint32(255));
green = bitand(bitshift(color, -8), uint32(255));
blue  = bitand(color, uint32(255));
fprintf('unpacked: %d %d %d\n', red, green, blue);
packed: 16746496 = #FF8800
unpacked: 255 136 0

Reinterpreting bytes: typecast and swapbytes

Converting with uint32(x) changes the value representation (rounding, clamping). typecast keeps the bytes exactly and only changes how they are read, which is what you need for binary file formats and network data:

matlab · try it yourself
bytes = uint8([1 0 0 0]);
disp(typecast(bytes, 'uint32'))
disp(typecast(uint8([0 1]), 'uint16'))
disp(typecast(uint16(258), 'uint8'))
f = typecast(single(1), 'uint32');
fprintf('single(1) is stored as 0x%s\n', dec2hex(f, 8));
disp(swapbytes(uint16(1)))
disp(typecast(int8(-1), 'uint8'))
1
256
  2  1
single(1) is stored as 0x3F800000
256
255

The results show that the computer is little-endian: the least significant byte comes first, so the bytes [1 0 0 0] read as the number 1. swapbytes reverses the byte order to read big-endian data. 0x3F800000 is the IEEE 754 single-precision pattern for 1.0: sign 0, exponent 127, fraction 0. And typecast(int8(-1), 'uint8') gives 255 because −1 in two's complement is all ones.

Learn more: Data Types & Classes, Images & Colormaps (where uint8 is everywhere) and Reading Numeric Data.

Test yourself

What is bitand(12, 10)?

  1. 8
  2. 14
  3. 6
  4. 2

What does uint8(3) - uint8(5) give?

  1. 0
  2. -2
  3. 254
  4. An error

What is the difference between uint32(x) and typecast(x, 'uint32') for x = single(1)?

  1. uint32 converts the value (giving 1); typecast reinterprets the 4 bytes (giving 1065353216)
  2. They are the same
  3. typecast rounds and uint32 doesn't
  4. uint32 reinterprets the bytes