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

3

2

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.

Licko answered 18/8, 2010 at 6:28 Comment(3)
enum is an integer type; it's not unsigned. What do you mean by "enum in binary representation"? Can you provide an example? Do you mean you want a type suitable for, say, bitmasks?Tented
Your question is not very clear. Note: The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int. Assuming enums are unsigned int is a not correct.Belak
I updated my question. Sorry for unclarity.Licko
J
3

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.

Juanajuanita answered 18/8, 2010 at 6:38 Comment(2)
You're right. I have to know exact spec of my compiler. I opened a new question for this: #3510052Licko
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.Saintly
T
1

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.

Tereasaterebene answered 18/8, 2010 at 6:45 Comment(0)
C
0

How about xdr - library routines for external data representation?

Reinventing the wheel rarely produces something better.

Coopt answered 18/8, 2010 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.