Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

Standard C does not provide access to the carry-out from shifts.
Some, not all, C implementations have processor-specific.h files or other extensions that do allow access.

Your should avoid using functionality from processor-specific.h files or extensions where practical. But if obliged to use, consider also writing a C Standard solution, at least as part of the documentation. see Recommended @Oli Charlesworth solution.

In general, to create effective portable code, one may need to view the problem at a higher level and not use carry outs. On the other hand, if this is for a narrow range of machines, go with what works for you (or those that pay your wage).

Various weaknesses were pointed out in my earlier posted examples. I see these now as implementation dependent. There are deleted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top