I'm aware that C++ has a ceiling function.

I was wondering how we might implement the ceil function in C++ for practise.

The method's signature is public static int ceil (float num)

I came up with an easy solution:

Convert num to a string, locate the decimal point's index, and see if the decimal component is bigger than zero.

Return num+1 if yes; else, return num.

But I don't want to use the string conversion.
Jun 13, 2022 in C++ 971 views

You can disassemble the components of an IEEE754 floating point number and put the logic together yourself:

```#include <cstring>

float my_ceil(float f)
{
unsigned input;
memcpy(&input, &f, 4);
int exponent = ((input >> 23) & 255) - 127;
if (exponent < 0) return (f > 0);
// small numbers get rounded to 0 or 1, depending on their sign

int fractional_bits = 23 - exponent;
if (fractional_bits <= 0) return f;
// numbers without fractional bits are mapped to themselves

unsigned integral_mask = 0xffffffff << fractional_bits;
unsigned output = input & integral_mask;
// round the number down by masking out the fractional bits

memcpy(&f, &output, 4);
if (f > 0 && output != input) ++f;
// positive numbers need to be rounded up, not down

return f;
}
```
• 4,960 points

edited Jun 14, 2022 by Hemant

How can I get the size of a C++ function?

In C++, how can I find the size& ...READ MORE

How to implement 2D vector array?

I'm using the vector class in the ...READ MORE

How to implement 2D vector array?

I'm using the vector class in the ...READ MORE

How can I get all the unique keys in a multimap

This method worked for me. for( multimap<char,int>::iterator it ...READ MORE

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

Invalid method parameters for eth_sendTransaction

params needs to be an array, try {"jsonrpc":"2.0","method":"eth_se ...READ MORE