[英]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
. 我正在学习C,我想知道是否可以在
uint64_t
内放置几个uint8_t
。
For instance let's say I want: 例如,假设我要:
1010 1010 (
uint8_t
)1010 1010(
uint8_t
)
and put it in a uint64_t
but at the "7th" position like: 并将其放在
uint64_t
但位于“第7个”位置,例如:
0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 1010 1010 0000 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 然后我可以添加另一个
uint8_t
1111 1111
1111 1111
but at the 0th position. 但在第0位
so: 所以:
0000 0000 1010 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111
0000 0000 1010 1010 0000 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
: 您需要先
to_be_added
(首先将location
值转换为bits ,而不是bytes ),然后再按位或将移位后的值转换为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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.