C 查找指向大内存块的指针的第n位
假设我有一个指向一大块内存的指针 我想得到指针右边的第n位C 查找指向大内存块的指针的第n位,c,C,假设我有一个指向一大块内存的指针 我想得到指针右边的第n位 void* start = malloc(1024*1024*1024); bool nthBit(int n) { return (int)((char*)start + n / 8) & (1 << n % 8); } void*start=malloc(1024*1024*1024); 布尔n位(整数n) { 返回(int)((char*)开始+n/8)和(1足够近!我会: bool nthBit(c
void* start = malloc(1024*1024*1024);
bool nthBit(int n)
{
return (int)((char*)start + n / 8) & (1 << n % 8);
}
void*start=malloc(1024*1024*1024);
布尔n位(整数n)
{
返回(int)((char*)开始+n/8)和(1足够近!我会:
bool nthBit(const void *raw, size_t n)
{
return *((const unsigned char*)raw + n / CHAR_BIT) & (1 << (n % CHAR_BIT));
// ^ ^^^^^^^^ - it will be 8, but communicates intent more clear
// ^ - actually access the pointer by dereferencing it
}
bool n位(常量无效*原始大小)
{
return*((const unsigned char*)raw+n/char_BIT)&(1尽量避免长时间的操作。引入中间变量,这些变量在一天结束时将由编译器优化
bool nthBitp(void *ptr, size_t n)
{
unsigned char *cptr = ptr;
unsigned char byte = cptr[n / CHAR_BIT];
return !!(byte & ( 1 << (n % CHAR_BIT)));
}
bool nthBitp(无效*ptr,大小)
{
无符号字符*cptr=ptr;
无符号字符字节=cptr[n/char_位];
return!!(byte&(1您可以执行以下操作:
bool test_bit(uint32_t* array , uint32_t idx){
uint32_t seg = idx / (sizeof(uint32_t) * 8) ;
uint32_t offset = idx % (sizeof(uint32_t) * 8);
uint8_t value = (array[seg] >> ((sizeof(uint32_t) * 8 - 1) - offset)) & 0x1 ;
return value != 0 ;
}
由于idx
是您的第n位。您必须取消引用raw
,您没有这样做“我无法将字符*转换为int”-因此只需首先取消引用char*
…而且,bool
只能是0
或1
,而不是1void*start=/code>(字符*)raw
我想你在这两个地方都指的是start
或raw
。不要硬编码“8”。虽然对于便携性来说可能不再需要硬编码了,但如果你使用CHAR\u BIT
(在中)对人类读者来说要明显得多。(关于:可移植性,我更多地考虑了8对9,但我怀疑有一些16位机器。因此,为了可移植性,使用它。)最好使用无符号字符。为什么这么复杂。如果长度不可除以sizeof(uint32_t)(您访问数组超出边界),那么在重拨最后一个uint32_t时,它是一个UB.一般来说