I have some bitfield:
int somefield : 15;
I'm trying to convert an int to 15 bit (can be positive or negative).
What is the best practice to do it efficiently?
I have some bitfield:
int somefield : 15;
I'm trying to convert an int to 15 bit (can be positive or negative).
What is the best practice to do it efficiently?
I'm trying to convert an int to 15 bit (can be positive or negative). What is the best practice to do it efficiently?
If the int
to convert is within the range of a 15-bit signed integer, simple use the following code. It is important not to use int
without signed
in defining the bit-field as this is one place in the C spec, it makes a difference. Without the signed
, an int
bit field could be implemented as unsigned
. It is implementation defined.
signed int somefield:15;
...
x.somefield = 12345;
int y = x.somefield;
If the int
to convert may be outside than the range of a 15-bit signed integer, better to use an unsigned
field to have portably consistent defined behavior. It is unclear what value OP wants to store when the int
is out-of-range. Some additional code may be needed should the sign need to be recovered. No additional overhead on writing and maybe overhead on reading depending on coding needs.
unsigned somefield:15;
...
x.somefield = 123456;
x.somefield = -1;
int y = x.somefield >= 0x4000 ? x.somefield - 0x8000 : x.somefield;
Alternatively, if the value to assign may be outside the bit-field range, insure the assignment does not happen. Additional overhead on writing and none on reading.
signed int somefield 15;
...
if (i >= INT15_MIN && i <= INT15_MAX) x.somefield = i;
else TBD();
int y = x.somefield;
chux, thanks a lot! I've found out another option, and it looks pretty simple too:
typedef struct {
unsigned int firstletter: 5;
unsigned int secondletter: 5;
unsigned int thirdletter: 5;
} data_in_32_format;
typedef struct {
unsigned int somedata: 15;
} data;
typedef union {
data_in_32_format;
data;
} common_data;
So, when I'm writing the data itself, I'm writing to the:
common_data entry;
entry.data = getint_in_decimal_format;
Than I'm printing it in 32 format:
print32("%c%c%c\n", entry.data_in_32_format.thirdletter
, entry.data_in_32_format.secondletter
, entry.data_in_32_format.firstletter);
Of cause I need to convert it to char correctly before previous (0-9 => numbers, >9 - letters, so in ASCII it is needed to be +55 to represent 32 bit format correctly (A for 10 and etc.).