0

I'm using a library passes me a pointer to an array of int32_T. I need to do some math on these numbers, but the data is actually in Q23.8 format.

I created a class overloading the basic math operators, but I'm stuck with how to cast the int32_t array pointer to my new class -- the datatypes are different sizes. Is there a way to do force my new class to match the size of int32_t, or is there another way to get this done?

Note: I want to avoid copying each item of this large array, as I'm developing for a resource constrained system.

1
  • In your class have a constructor that takes a int32_t. You could then cast a single element of the array to your class in order to operate on it. Commented Jun 3, 2015 at 20:59

1 Answer 1

1

First of all, please note that if you are not constrained by performance, only by memory consumption, the solution suggested by @Aumnayan may be preferable for simplicity and portability.

In order to force your objects to match the size int32_t and alignment of Q23.8 you can use bit-fields:

struct Q_23_8
{
    int32_t fractional :  8;
    int32_t integral   : 23;
};

static_assert(sizeof(Q_23_8) == sizeof(int32_t), "Sizes differ!");

Please note that the order of fields depends on target CPU endianness; the sample is for little-endian. Also, to ensure the size of your class you may need to use your compiler's packing and alignment control capabilities (e g. #pragma pack).

Having int32_t encoded[] you can interpret it as an array of Q_23_8 as follows:

Q_23_8* decoded = reinterpret_cast<Q_23_8*>(encoded);

Here is a complete code sample: http://ideone.com/X177fQ. I strongly suggest reading more about bit-fields, their portability, and limitations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.