1

I am trying to write a very efficient C++ class that defines a new floating point type with much more precision than the primitive data types. See my previous post for more background.

To start I am using static allocation in my hp_float.hpp:

class hp_float {
private:
  unsigned char buf[48];
public:
  hp_float();
  hp_float operator+(const hp_float& h);
};

My problem is that, eventually, in order to implement that operator+ I am going to have to use bit-wise operations including << and >>. I saw that this can be tricky with these buffers, as seen in this SO post.

I would like to do shifting without the need for a loop. I could manually unroll it in my implementation, but ultimately I want to treat the buffer as a contiguous string of bits like any other primitive data type:

hp_float hp_float::operator+(const hp_float& h) {
  [type???] this_sign = buf >> (48*8-1);

  ...
}

My Question: Is this not possible? Do have any advice one doing what I want with the best performance?

redmoncoreyl
  • 133
  • 9
  • Note that in many cases, the compiler/optimizer will automatically unroll any loop you come up with, if it thinks it's worthwhile to do so -- therefore avoiding loops in your source code may not be so important anyway. – Jeremy Friesner Jan 21 '19 at 01:51
  • 1
    `std::bitset` maybe? – Shawn Jan 21 '19 at 02:56
  • Oh, I didn’t know about `std::bitset`. And it looks like from the notes at the bottom of the cppreference that it is static allocation if the size is known at compile time. Is that correct? – redmoncoreyl Jan 21 '19 at 03:35
  • 1
    @redmoncoreyl `std::betset`'s size _must_ be known at compile time since it's a template parameter. Also, the `noexcept` guarantee of its constructor effectively means its storage can't be dynamically allocated. – Miles Budnek Jan 21 '19 at 03:58
  • If you are looking for speed concerning bit shift I would consider to change your array type. `unsigned char` looks like you intend to process the data byte wise. That means every byte is converted to `unsigned` before any arithmetic operation (including bit shift) and converted back when stored (although the "conversions" are probably trivial). If you make your array instead of `unsigned int` you will process much more bits per iteration step (and there is no conversion in arithmetic operations, even no trivial). If you have to consider carries then `unsigned short` could be a compromise. – Scheff's Cat Jan 21 '19 at 07:10
  • "string" of bits? Series of bits? – user997112 Jan 28 '19 at 17:09
  • I was thinking of a [mathematical string](http://mathworld.wolfram.com/String.html). – redmoncoreyl Jan 28 '19 at 19:16

0 Answers0