Jeremy Salwen - 1 year ago 104

C Question

I'm looking to take an IEEE double and remove any integer part of it in the most efficient manner possible.

I want

`1035 ->0`

1045.23->0.23

253e-23=253e-23

I do not care about properly handling denormals, infinities, or NaNs. I do not mind bit twiddling, as I know I am working with IEEE doubles, so it should work across machines.

Branchless code would be much preferred.

My first thought is (in pseudo code)

`char exp=d.exponent;`

(set the last bit of the exponent to 1)

d<<=exp*(exp>0);

(& mask the last 52 bits of d)

(shift d left until the last bit of the exponent is zero, decrementing exp each time)

d.exponent=exp;

But the problem is that I can't think of an efficient way to shift d left until the last bit of the exponent is zero, plus it seems it would need to output zero if all of the last bits weren't set. This seems to be related to the base 2 logarithm problem.

Help with this algorithm or any better ones would be much appreciated.

I should probably note that the reason I want branchless code is because I want it to efficiently vectorize.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

How about something simple?

```
double fraction = whole - ((long)whole);
```

This just subtracts the integer portion of the double from the value itself, the remainder should be the fractional component. It's possible, of course, this could have some representation issues.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**