• Forum
  • Lounge
  • Portable way of bit masking in C (or C++

 
Portable way of bit masking in C (or C++)

In my book, I have an exercise that asks me to take an int x (like 0x12345678) and return another int with all but the least significant byte to be changed to FF (like 0xFFFFFF78).

So far so good. I implemented it as follows and it works:

1
2
3
4
5
6
7
8
#include <stdio.h>

int main()
{
    int x = 0x12345678;
    printf( " %.2x\n", x | 0xFFFFFF00 );
    return 0;
}


The catch here is that it says your code should not assume any 'word size'.

Although our examples assume a 32-bit word size, your code should work for any word size >= 8


How can I incorporate this 'portability' issue?

Thanks!
Last edited on
x | ~0xFF

By the way, you should be careful when doing bit twiddling with signed values, and do it with unsigned values whenever possible.
Aah Thanks helios

Was struggling with this!

And thanks for the suggestion on signed vs unsigned values as well!
A somewhat ugly solution would be casting the int to char* then use a for() loop, or std::fill(), or std::fill_n() if you want to be fancy.

Have you learned about endianness yet?
http://en.wikipedia.org/wiki/Endianness

http://www.cplusplus.com/reference/algorithm/fill/
http://www.cplusplus.com/reference/algorithm/fill_n/

1
2
3
4
5
6
7
8
9
10
11
int x = 0x12345678;
char *tp = reinterpret_cast<char *> (x);

if (/* Little-Endian machine */)
{
    std::fill_n(tp + 1, sizeof x - 1, 0xFF);
}
else /* Big-Endian machine */
{
    std::fill_n(tp, sizeof x - 1, 0xFF);
}


Disclaimer: code above was not tested.
Topic archived. No new replies allowed.