簡體   English   中英

在C中的uint64_t中設置一點

[英]Setting a bit in an uint64_t in c

您好,我想在pos(從左到右)處設置一個(值)。 這是我的代碼,不適用於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。

//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

要設置posvalue ,請使用

value |= ((uint64_t)1) << pos;

您的其余代碼應該做什么?

有關更新的問題,請參見此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM