bitset

Sets or clears bits of an integer at given positions.

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

C = bitset(A, n)

Sets bit n of A to 1.

C = bitset(A, n, v)

Sets bit n to v: 1 turns it on, 0 turns it off.

Description

Because bit 1 has the value 1, bit 2 the value 2 and bit 3 the value 4, bitset(uint8(0), 3) is 4. Setting a bit that is already set, or clearing one that is already clear, leaves the value unchanged.

Several positions can be given at once in n.

Input arguments

A
Array of nonnegative integers.
n
Bit position, counted from 1 at the least significant bit.
v
Value to store, 0 or 1. The default is 1.

Output arguments

C
Array of the same class as A with the bit changed.

Example

bitset(uint8(0), 3)
bitset(uint8(15), 1, 0)
bitset(0, [1 2 3])
Output
ans = uint8
   4
ans = uint8
   14
ans = 1×3

     1     2     4

See also

bitget bitor bitand bitshift