Skip to main content
edited tags
Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238
Tweeted twitter.com/#!/StackCodeReview/status/374460639777144832
Source Link
mitya221
  • 803
  • 6
  • 11
  • 14

Split a long integer into eight 4-bit values

It's an exercise from a book. There is a given long integer that I should convert into 8 4-bit values. The exercise is not very clear for me, but I think I understood the task correctly.

I googled how to return with an array in a function. In the splitter function I add the last 4 bits into the values array, then cut the them from the original number.

Is this a good way to do this?

#include <iostream>

int * splitter(long int number)
{
    static int values[8];

    for (int i = 0; i < 8; i++)
    {
        values[i] = (int)(number & 0xF);
        number = (number >> 4);
    }

    return values;
}

int main()
{
    long int number = 432214123;
    int *values;
    values = splitter(number);
    for (int i = 7; i >= 0; i--)
        std::cout << values[i] << " ";
    return 0;
}