views:

361

answers:

3

I am using signed to unsigned byte(int8_t) cast to pack byts.

uint32_t(uint8_t(byte)) << n

This works using GCC on Intel Linux. Is that portable for other platforms/compilers, for example PowerPC? is there a better way to do it? using bitset is not possible in my case. I am using stdint via boost

+3  A: 

It's not portable, as the types uint32_t and uint8_t are not part of the C++ Standard. All such maipulations are inherently implementation dependent.

anon
Note: These types are part of the C99 standard, though.
Josef Grahn
So long as these types are what they appear to be, then there is in practice no problem. It would be a perverse system that defined uint8_t as a 32bit signed type for example! In a system without C99's <stdint.h>, implementing your own is feasible. Portable in that the code will run, not portable in the sense that the data will have teh same byte order between architectures.
Clifford
The OP says he is using boost stdint, so it *is* portable. It's just not standard. The typedefs in `boost/cstdint.hpp` are portable.
Charles Salvia
it's portable. portable != standard.
Samuel_xL
The original question made no mention of Boost.
anon
sorry, I have forgot to mention boost
aaa
He also titled it C/C++, but if using boost, then only C++ applies. Correct tag, bad title.
Clifford
+2  A: 

If you are using boost/cstdint.hpp from the Boost Integer library, then yes, the typedefs are portable (cross-platform.) The boost/cstdint.hpp header is meant to implement C99 stdint.h functionality in C++.

From the Boost documentation:

The header provides the typedef's useful for writing portable code that requires certain integer widths. All typedef's are in namespace boost.

Charles Salvia
+1  A: 

In practice, yes it's most likely going to work on most other platforms you encounter (especially if Boost is ported to it). However, if you are writing these packed values to files or network sockets, you'll have to deal with byte order (your example of PowerPC has big-endian byte order while Intel have little-endian). In that respect, the code will behave differently on different hardware architectures.

Josef Grahn