2

For example:

1. To convert 32-bit IP address (IPv4):

unsigned char ByteAddress[4];
unsigned int* IntegerAddress;

IntegerAddress = reinterpret_cast<unsigned int*> &ByteAddress ;

Then I can use IntegerAddress to compare ip addresses.

2. To convert 128-bit IP address (IPv6):

unsigned char ByteAddress[16];
uint64_t* LongAddress;

LongAddress = reinterpret_cast<uint64_t*> &ByteAddress

Then I can use LongAddress [0] and LongAddress[1] to compare ip addresses.

Is it preferred over using bit shift operators (as it is quicker) ? Is it good programming practice? Would it work for all platforms (especially unix and windows 64) and compilers (C++, VS2010)

Atul
  • 3,778
  • 5
  • 47
  • 87
  • 1
    I'd prefer c++ casting with `reinterpret_cast()` in c++ code, but should be portable as long as you have the same endianess – Theolodis Apr 23 '14 at 07:17
  • I edited it as you suggested. But my main intention is, is it preferred approach of conversion over using bit shift operators. – Atul Apr 23 '14 at 07:22
  • @Theolodis It's not portable, there's platform that won't handle that if the char array isn't suitable aligned. – nos Apr 23 '14 at 07:23
  • `int` isn't the same size as `char[4]` on *all* platforms. Example: In 16-bit Windows programs, `int` is 16 bits. It will work on many platforms, though. – Klas Lindbäck Apr 23 '14 at 07:35
  • You should be aware that the IP address as transported over the network (and as used in the socket structures) is in network (aka big endian) byte order. You may need to use the [ntohl()](http://linux.die.net/man/3/ntohl) function to get the correct integer representation for your machine architecture. – πάντα ῥεῖ Apr 23 '14 at 07:36

1 Answers1

0

I think, you can use unions for that

union Int32And4Bytes {
int32_t IntegerValue;
unsigned char ByteArray[4];
};

It should be aligned correctly, IIRC.

dreamer
  • 136
  • 1
  • I had thought of this initially but there is lot of confusion over use of union for reinterpretation of data. Many says that results will be unpredictable depends on compilers and platforms. For example: http://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c – Atul Apr 23 '14 at 07:37
  • The most correct way is to use bit shift operations. But you should detect endianess. – dreamer Apr 23 '14 at 08:02
  • Shift operators works regardless of endianness: http://stackoverflow.com/questions/1041554/bitwise-operators-and-endianness – Atul May 05 '14 at 18:05
  • This does not work in C++ due to type punning. It violates the standard (it's valid in C only). It might work in some compilers but you shouldn't depend on it. – The Quantum Physicist Mar 24 '19 at 10:55