您好,我想在pos(从左到右)中设置一个位(value)。这是我的代码,不适用于uint64_t(这里应该返回0而不是1),但是当我更改值以使其对uint8_t起作用(具有相同的逻辑)时,它可以工作。有任何想法吗?拜托。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
int main()
{
uint64_t x = (uint64_t)1;
int pos = 63;
bool value = 0;
uint8_t z = x;
z = z >> (64-pos);
z = z << (64-pos);
uint64_t a = (uint64_t)1;
uint64_t d = (uint64_t)0;
uint64_t y;
uint64_t c = d;
uint64_t b = x;
b = b << (pos+1);
b = b >> (pos+1);
if (value == 1)
{
y = a;
y = y << (63-pos);
}
else
{
y=d;
}
c = c|z|y|b;
printf("%lld",c);
return c;
}
编辑:我认为有一个误解(我还不够清楚,我的坏处),实际上我有一个x,它是一个uint64_t,我有一个int pos,它是x中一位的位置,我值为布尔值(1或0),如果value为1,则x中pos的位必须变为/保持1;如果value为0,则x中pos的位必须变为/保持0。
答案 0 :(得分:2)
//sets the bit pos to the value. if value is == 0 it zeroes the bit if value !=0 it sets the bit
void setbit(uint64_t *val, int bit, int value)
{
if(value)
{
*val |= ((uint64_t)1 << bit);
}
else
{
*val &= ~((uint64_t)1 << bit);
}
}
//sets nbits at location pos to the value of the first nbits of the value parameter.pos + nbits < 63
void setbits(uint64_t *val, int pos, int nbits, uint64_t value)
{
uint64_t mask = ((uint64_t)((uint64_t)1 << nbits) - 1);
*val &= ~(mask << pos);
*val |= (val & mask) << pos;
}
以及bool的用法
#include <stdbool.h>
uint64_t obj;
/* ... */
setbit(&obj, 5, true); //sets the 5th bit to 1
setbit(&obj, 7, false); //sets the 7th bit to 0
答案 1 :(得分:2)