简体   繁体   中英

Put uint8_t inside of a uint64_t

I'm learning about C and I was wondering if it's possible to put several uint8_t s inside of a uint64_t .

For instance let's say I want:

1010 1010 ( uint8_t )

and put it in a uint64_t but at the "7th" position like:

0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

And later down the line I could add in another uint8_t like

1111 1111

but at the 0th position.

so:

0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111

This is what I've tried but there are errors because they're different types.

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    // Somehow put at a location?
    bits = bits << location;
    bits = bits & to_be_added;
}

You have the right general idea, but there are a couple of errors in your code. You need to shift to_be_added first (converting the location value to bits , not bytes , first), and then bitwise OR the shifted value into bits :

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits |= ((uint64_t)to_be_added << (location * CHAR_BIT));
}
void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits = *bits | (((uint64_t)to_be_added) << (location*8));
}

Why not use a union? (If you dont't have to wonder about endianess of course)

typedef union
{
    struct
    {
        uint8_t Byte0;
        uint8_t Byte1;
        uint8_t Byte2;
        uint8_t Byte3;
        uint8_t Byte4;
        uint8_t Byte5;
        uint8_t Byte6;
        uint8_t Byte7;
    };
    uint64_t complete;
}My_uint64T;

My_uint64_t bits;

.....
   //no you could do :



bits.complete = ob0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000;
bits.Byte7 = 0b11111111;

Even if more verbose than the proposed solutions, you may try with unions and arrays to keep you code pretty clean:

void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added) {
    union {
        uint64_t u64;
        uint8_t u8[8];
    } t;

    t.u64 = *bits;
    t.u8[location] = to_be_added;

    *bits = t.u64;
}
void addToBitsAtPosition(uint8_t location, uint64_t *bits, uint8_t to_be_added)
{
    *bits = *bits | (to_be_added << (location*8));
}

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