What type should I use for binary representation of C enum?

岁酱吖の 提交于 2019-12-13 16:31:11

问题


As I know C enum is unsigned integer, but this may vary by implementation. What type should I use for the enum in binary representation?

*PS 'binary representation' means byte-array. I want to serialize enum values to socket to inter-operate with other programs.


回答1:


It's up to the compiler to use an int to represent an enum type, or a long if an int is not sufficient to hold all the values of the enum.

If you know that all your enum values can be represented by an int, then you can safely use int as the binary representation of your enum values.




回答2:


As enums are just fancy ways to set integers, you should go for an integer type big enough to store all you enum values. Normally, a char should suffice and then there are no serialization issues. But I'd go for a short or a long instead. When serializing, I'd use ntohs/htons or ntohl/htonl (see their man pages) to always make sure the serialization is in network byte order and the deserialization is in host byte order.




回答3:


How about xdr - library routines for external data representation?

Reinventing the wheel rarely produces something better.



来源:https://stackoverflow.com/questions/3509470/what-type-should-i-use-for-binary-representation-of-c-enum

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