Ints to Bytes: Endianess a Concern?

▼魔方 西西 提交于 2019-12-25 01:46:42

问题


Do I have to worry about endianness in this case (integers MUST be 0-127):

    int a = 120;
    int b = 100;
    int c = 50;
    char theBytes[] = {a, b, c};

I think that, since each integer sits in its own byte, I don't have to worry about Endianess in passing the byte array between systems. This has also worked out empirically. Am I missing something?


回答1:


Endianness only affects the ordering of bytes within an individual value. Individual bytes are not subject to endian issues, and arrays are always sequential, so byte arrays are the same on big- and little-endian architectures.

Note that this doesn't necessarily mean that only using chars will make datatypes 100% byte-portable. Structs may still include architecture-dependent padding, for example, and one system may have unsigned chars while another uses signed (though I see you sidestep this by only allowing 0-127).




回答2:


No, you don't need to worry, compiler produces code which makes correct casting and assignment.



来源:https://stackoverflow.com/questions/3710669/ints-to-bytes-endianess-a-concern

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