C、C++设置数组bit位

通过函数设置数组中某个bit位的值,函数声明如下:

/**
 * @brief setArrayBits 设置数组bit8
 * @param array 要设置的数组
 * @param arrayLength 数组长度
 * @param value 要设置的值
 * @param bitStart bit起始位
 * @param bitLength bit长度
 */
void setArrayBits(uint8_t* array,
                  uint8_t arrayLength,
                  uint64_t value,
                  uint8_t bitStart,
                  uint8_t bitLength);

 

函数体实现如下(由于计算机设置值不支持跨字节设置,所以先找到对应的起始字节号和终止字节号,通过特定的数据类型进行位操作,完成bit位的设置):

void setArrayBits(uint8_t *array, uint8_t arrayLength, uint64_t value,
                  uint8_t bitStart, uint8_t bitLength)
{
    //计算bit所占字节数
    int bitEnd     = bitStart + bitLength;
    int byteStart  = bitStart/8;
    int byteEnd    = bitEnd/8;
    int byteLength = byteEnd - byteStart;

    if(byteLength == 0){
        //转换为可定义的2的n次方的数据
        uint8_t tmp = value;
        //计算需要左移的位数,并左移
        int leftShift = bitStart % 8;
        tmp = tmp<<leftShift;
        //计算原始数据所在字节位

        //拷贝原始数据
        uint8_t origByteValue = 0;
        memcpy(&origByteValue, &array[byteStart], sizeof(uint8_t));

        //按位或
        uint8_t newByteValue = origByteValue | tmp;

        //将值拷贝回去
        memcpy(&array[byteStart], &newByteValue, sizeof(uint8_t));
    }

    else if(byteLength == 1){
        //转换为可定义的2的n次方的数据
        uint16_t tmp = value;
        //计算需要左移的位数,并左移
        int leftShift = bitStart % 8;
        tmp = tmp<<leftShift;
        //计算原始数据所在字节位

        //拷贝原始数据
        uint16_t origByteValue = 0;
        memcpy(&origByteValue, &array[byteStart], sizeof(uint16_t));

        //按位或
        uint16_t newByteValue = origByteValue | tmp;

        //将值拷贝回去
        memcpy(&array[byteStart], &newByteValue, sizeof(uint16_t));
    }
    else if(byteLength > 1 && byteLength < 4){
        //转换为可定义的2的n次方的数据
        uint32_t tmp = value;
        //计算需要左移的位数,并左移
        int leftShift = bitStart % 8;
        tmp = tmp<<leftShift;
        //计算原始数据所在字节位

        //拷贝原始数据
        uint32_t origByteValue = 0;
        memcpy(&origByteValue, &array[byteStart], sizeof(uint32_t));

        //按位或
        uint32_t newByteValue = origByteValue | tmp;

        //将值拷贝回去
        memcpy(&array[byteStart], &newByteValue, sizeof(uint32_t));
    }
    else if(byteLength >= 4 && byteLength < 8){
        //转换为可定义的2的n次方的数据
        uint64_t tmp = value;
        //计算需要左移的位数,并左移
        int leftShift = bitStart % 8;
        tmp = tmp<<leftShift;
        //计算原始数据所在字节位

        //拷贝原始数据
        uint64_t origByteValue = 0;
        memcpy(&origByteValue, &array[byteStart], sizeof(uint64_t));

        //按位或
        uint64_t newByteValue = origByteValue | tmp;

        //将值拷贝回去
        memcpy(&array[byteStart], &newByteValue, sizeof(uint64_t));
    }


}

 

posted on 2025-02-05 14:13  明太宗朱棣  阅读(55)  评论(0)    收藏  举报

导航