简体   繁体   中英

Setting a bit in an uint64_t in c

Hello I would like to set a bit ( value ) at a pos ( from left to right ). Here is my code that doesn't work for uint64_t ( here it should return 0 and not 1 ) but when I change values to make it works ( with the same logic ) with uint8_t it works. Any ideas? Please.

#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;
}

EDIT : I think there is a misunderstood ( I haven't be clear enough, my bad ), actually I have x that is an uint64_t and I have a int pos that is the position of one bit in x, and I have value that is a boolean ( 1 or 0 ) and if value is 1 the bit at the pos in x must become/stay 1 and if value is 0 the bit at the pos in x must become/stay 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;
}

And usage with 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

To set the bit pos in value , you use

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

What is the rest of your code supposed to do?

For the updated question, see this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM