Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C hold the carry about bit from a << or a >> bit shift?

I read that C holds the carry-out from shifts and it can be found in processor-specific .h.

Is this true and should I use it? or should work out the carry-out bit myself ?

like image 634
cxzp Avatar asked Oct 12 '25 15:10

cxzp


1 Answers

There is no standard way to access the carry bit(s) of primitive operations in C.

You will either need to perform the shift in a larger data type:

uint16_t foo = ...;

uint32_t tmp = (uint32_t)foo << shift;
uint16_t result = (uint16_t)tmp;
uint16_t carry  = (uint16_t)(tmp >> 16);

or by performing the opposite shift:

uint16_t result = foo << shift;
uint16_t carry  = foo >> (16 - shift);

Note that this second method invokes undefined behaviour if shift == 0, so you'd need to handle that case separately.

like image 152
Oliver Charlesworth Avatar answered Oct 14 '25 06:10

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!