_bittestandset, _bittestandset64

Microsoft Specific

Generate the bts instruction, which examines bit b of the address a, returns its current value, and sets the bit to 1.

unsigned char _bittestandset(
   long *a,
   long b
);
unsigned char _bittestandset64(
   __int64 *a,
   __int64 b
);

Parameters

  • [in, out] a
    A pointer to the memory to examine.

  • [in] b
    The bit position to test.

Return Value

The bit at the position specified.

Requirements

Intrinsic

Architecture

_bittestandset

x86, IPF, x64

_bittestandset64

IPF, x64

Header file <intrin.h>

Remarks

On the IPF architecture, the bts instruction is not available, so this intrinsic is a custom function that imitates the behavior of bts. This custom function might be slower than a hand-written inline function because it includes overhead, such as handling the case where b is negative, that might be unnecessary in specific cases.

This routine is only available as an intrinsic.

Example

// bittestandset.cpp
// processor: x86, IPF, x64
// This example uses several of the _bittest family of intrinsics
// to implement a Flags class that allows bit level access to an
// integer field.
#include <stdio.h>
#include <intrin.h>

#pragma intrinsic(_bittestandset, _bittestandreset,\
                  _bittestandcomplement, _bittest)

class Flags
{
private:
    long flags;
    long* oldValues;

public:
    Flags() : flags(0)
    {
        oldValues = new long[32];
    }

    ~Flags()
    {
        delete oldValues;
    }

    void SetFlagBit(long nBit)
    {
        // We omit range checks on the argument
        oldValues[nBit] = _bittestandset(&flags, nBit);
        printf_s("Flags: 0x%x\n", flags);
    }
    void ClearFlagBit(long nBit)
    {
        oldValues[nBit] = _bittestandreset(&flags, nBit);
        printf_s("Flags: 0x%x\n", flags);
    }
    unsigned char GetFlagBit(long nBit)
    {
        unsigned char result = _bittest(&flags, nBit);
        printf_s("Flags: 0x%x\n", flags);
        return result;
    }
    void RestoreFlagBit(long nBit)
    {
        if (oldValues[nBit])
            oldValues[nBit] = _bittestandset(&flags, nBit);
        else
            oldValues[nBit] = _bittestandreset(&flags, nBit);
        printf_s("Flags: 0x%x\n", flags);     
    }
    unsigned char ToggleBit(long nBit)
    {
        unsigned char result = _bittestandcomplement(&flags, nBit);
        printf_s("Flags: 0x%x\n", flags);
        return result;
    }
};

int main()
{
    Flags f;
    f.SetFlagBit(1);
    f.SetFlagBit(2);
    f.SetFlagBit(3);
    f.ClearFlagBit(3);
    f.ToggleBit(1);
    f.RestoreFlagBit(2);
}

Flags: 0x2 Flags: 0x6 Flags: 0xe Flags: 0x6 Flags: 0x4 Flags: 0x0

See Also

Reference

Compiler Intrinsics