Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. View or edit the community-maintained wiki page associated with this page.

# core.bitop

This module contains a collection of bit-level operations.

Authors:
Don Clugston, Sean Kelly, Walter Bright, Alex Rønne Petersen

Source:
core/bitop.d

pure nothrow @nogc @safe int bsf(size_t v);
Scans the bits in v starting with bit 0, looking for the first set bit.

Returns:
The bit number of the first bit set. The return value is undefined if v is zero.

Example:
```import core.bitop;

int main()
{
assert(bsf(0x21) == 0);
return 0;
}
```

pure nothrow @nogc @safe int bsr(size_t v);
Scans the bits in v from the most significant bit to the least significant bit, looking for the first set bit.

Returns:
The bit number of the first bit set. The return value is undefined if v is zero.

Example:
```import core.bitop;

int main()
{
assert(bsr(0x21) == 5);
return 0;
}
```

pure nothrow @nogc @system int bt(in size_t* p, size_t bitnum);
Tests the bit. (No longer an intrisic - the compiler recognizes the patterns in the body.)

Examples:
```size_t array;

array = 2;
array = 0x100;

assert(bt(array.ptr, 1));
assert(array == 2);
assert(array == 0x100);
```

pure nothrow @nogc @system int btc(size_t* p, size_t bitnum);
Tests and complements the bit.

pure nothrow @nogc @system int btr(size_t* p, size_t bitnum);
Tests and resets (sets to 0) the bit.

pure nothrow @nogc @system int bts(size_t* p, size_t bitnum);
Tests and sets the bit.

Parameters:
 size_t* p a non-NULL pointer to an array of size_ts. size_t bitnum a bit number, starting with bit 0 of p, and progressing. It addresses bits like the expression: ```p[index / (size_t.sizeof*8)] & (1 << (index & ((size_t.sizeof*8) - 1))) ```

Returns:
A non-zero value if the bit was set, and a zero if it was clear.

Examples:
```size_t array;

array = 2;
array = 0x100;

assert(btc(array.ptr, 35) == 0);
if (size_t.sizeof == 8)
{
assert(array == 0x8_0000_0002);
assert(array == 0x100);
}
else
{
assert(array == 2);
assert(array == 0x108);
}

assert(btc(array.ptr, 35));
assert(array == 2);
assert(array == 0x100);

assert(bts(array.ptr, 35) == 0);
if (size_t.sizeof == 8)
{
assert(array == 0x8_0000_0002);
assert(array == 0x100);
}
else
{
assert(array == 2);
assert(array == 0x108);
}

assert(btr(array.ptr, 35));
assert(array == 2);
assert(array == 0x100);
```

pure nothrow @nogc @safe uint bswap(uint v);
Swaps bytes in a 4 byte uint end-to-end, i.e. byte 0 becomes byte 3, byte 1 becomes byte 2, byte 2 becomes byte 1, byte 3 becomes byte 0.

nothrow @nogc @system ubyte inp(uint port_address);
nothrow @nogc @system ushort inpw(uint port_address);
nothrow @nogc @system uint inpl(uint port_address);