Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast signed int to 15 bit bit-field?

Tags:

c

bit-fields

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?

like image 424
mibo6700 Avatar asked Mar 17 '16 15:03

mibo6700


1 Answers

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;
like image 76
chux - Reinstate Monica Avatar answered Nov 12 '22 00:11

chux - Reinstate Monica