views:

58

answers:

3

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  A: 

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.

Didier Trosset
You're right. I have to know exact spec of my compiler. I opened a new question for this: http://stackoverflow.com/questions/3509552/whats-the-data-type-of-c-enum-of-clang-compiler
Eonil
Hm, I don't think that it may be `long` for that reason, but maybe the specification allows it to be `long`. All enumeration type constants are by definition `int`, so `int` will always be able to hold all values.
Jens Gustedt
A: 

How about xdr - library routines for external data representation?

Reinventing the wheel rarely produces something better.

domen
+1  A: 

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.

DarkDust