我试图从核心基金会CFDataRef获取N个最左边的位.CF和C的新手,以下是我目前掌握的内容.它正在打印0,所以有问题.

int get_N_leftmost_bits_from_data(int N)
{
    // Create a CFDataRef from a 12-byte buffer
    const unsigned char * _Nullable buffer = malloc(12);
    const CFDataRef data = CFDataCreate(buffer, 12);

    const unsigned char *_Nullable bytesPtr = CFDataGetBytePtr(data);

    // Create a buffer for the underlying bytes
    void *underlyingBytes = malloc(CFDataGetLength(data));

    // Copy the first 4 bytes to underlyingBytes
    memcpy(underlyingBytes, bytesPtr, 4);

    // Convert underlying bytes to an int
    int num = atoi(underlyingBytes);

    // Shift all the needed bits right
    const int numBitsInByte = 8;
    const int shiftedNum = num >> ((4 * numBitsInByte) - N);

    return shiftedNum;
}

谢谢你的帮助!

推荐答案

因为您只关心前四个字节中的位,所以您可以将字节复制到一个整数,然后对该整数执行位移位.


#include <string.h>
#include <stdint.h>
int main(){
    
    uint8_t bytes[12] = {0};
    for(int n = 0; n < sizeof(bytes) ; ++n){
        bytes[n] = n+0xF;
        //printf("%02x\n",bytes[n]);
    }
    uint32_t firstfour = 0;
    //copy the first four bytes
    memcpy(&firstfour,bytes,sizeof(uint32_t));
    //get the left most bit
    uint32_t bit = firstfour>>31&1;
    
    return 0;
}

您仍然可以在CF中执行memcpy

C++相关问答推荐

Zig将std.os.argv转换为C类型argv

DPDK-DumpCap不捕获端口上的传入数据包

仅在给定的大小和对齐方式下正确创建全局

LONG_DOUBLE_T是否存在(标准C:C23)

试图从CSV文件中获取双精度值,但在C++中始终为空

在每种If-Else情况下执行语句的最佳方式

CGO:如何防止在使用CGO在包中包含C头文件时出现多个定义...&q;错误?

如何计算打印二叉搜索树时每行所需的空间?

为什么数组的最后一个元素丢失了?

C语言中MPI发送接收字符串时出现的分段错误

为什么我在C代码中得到一个不完整的类型?

隐藏测试用例无法在c程序中计算位数.

如何使用WRITE()以指针地址的十六进制形式写入标准输出

Dlsym()的手册页解决方法仍然容易出错?

C:面筋蛋白';为什么不刷新窗口?

C中的空指针是什么(_N)?

浮点正零何时不全为零?

为什么argc和argv即使在主函数之外也能工作?

execve 不给出which命令的输出

nullptr_t 是否会 destruct 类型双关或指针转换?