portable signed/unsigned byte cast,C++

时光怂恿深爱的人放手 提交于 2019-12-24 07:43:23

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1862453/portable-signed-unsigned-byte-cast-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!