0

I have a short code snippet in C++ and I need to have the same functionality in C#:

typedef enum {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3} eIM;
#define htonl(x)  ( ( ( ( x ) & 0x000000ff ) << 24 ) | \
                    ( ( ( x ) & 0x0000ff00 ) << 8  ) | \
                    ( ( ( x ) & 0x00ff0000 ) >> 8  ) | \
                    ( ( ( x ) & 0xff000000 ) >> 24 ) )

int value = htonl(eV);

Unfortunately I'm no big programmer, so I need some help.

3
  • For the sake of completeness, there's not a literal translation from your code to C# because C# doesn't support preprocessor macros. Mark H does provide the same functionality, though. Commented Aug 17, 2010 at 17:56
  • For the record, not all C++ programmers write code that bad. (Yuck.) Commented Aug 17, 2010 at 18:17
  • The original code had more meaningful variable names, but I obfuscated them so it's less obvious where this is from. Commented Aug 17, 2010 at 18:43

3 Answers 3

5
enum eIM { eD = 0, eV, eVO, eVC }
int value = System.Net.IPAddress.HostToNetworkOrder((int)eIM.eV);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I will try that tomorrow. Are the other enums numbered automatically?
@asdrubael - yes, in both C# and C++. The = 0 isn't necessary either as it is default, but it can help for readability to have the numbers there if you want em.
0

Well, remember that C# is managed code, so you shouldn't try to do bit manipulation too much with it. And, C# complained that I needed to use unsigned integers in my code, but try:

uint htonl(uint i)
{
    return (((i & 0x000000ff) << 24) | ((i & 0x0000ff00) << 8) | ((i & 0x00ff0000) >> 8) | ((i & 0xff000000) >> 24));
}

Comments

0
public enum eIM {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3}

public static class ByteReverser
{
    public static uint ReverseBytes(uint value)
    {
        return (uint)((uint)((value & 0x000000ff) << 24) |
                      (uint)((value & 0x0000ff00) << 8) |
                      (uint)((value & 0x00ff0000) >> 8) |
                      (uint)((value & 0xff000000) >> 24));
    }
}

And, later:

var value = ByteReverser.ReverseBytes((uint)eIM.eV);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.