#include <assert.h>
#include <stdlib.h>
typedef struct {
char x1 : 1;
char x2 : 1;
char x3 : 1;
char x4 : 1;
char x5 : 1;
char x6 : 1;
char x7 : 1;
char x8 : 1;
unsigned int an_int;
} my_struct;
int main(int argc, const char* argv[])
{
int input_value;
my_struct x_struct;
assert(argc == 2);
input_value = strtol(argv[1], NULL, 10);
assert(0 <= input_value && input_value < 16);
x_struct.x3 = (input_value >> 0) & 0x01;
x_struct.x4 = (input_value >> 1) & 0x01;
x_struct.x5 = (input_value >> 2) & 0x01;
x_struct.x6 = (input_value >> 3) & 0x01;
return 0;
}
Setting groups of bits from a structure to a value
Domanda
Let's say I have this structure:
typedef struct {
char x1 : 1;
char x2 : 1;
char x3 : 1;
char x4 : 1;
char x5 : 1;
char x6 : 1;
char x7 : 1;
char x8 : 1;
unsigned int an_int;
} my_struct;
I want to modify the group made by the bits x3
, x4
, x5
, x6
to value between 0
and 15
, value read from stdin
(and the rest of the values being 0).
How do I do that?
(for example, in int main()
I have my_struct x_struct
, and I want to modify x3
, x4
, x5
, x6
of it).
Any help?
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow