Alexander Eldin
Alexander Eldin

Reputation: 3

C# Negative IP Address to dotted decimal using intel standards conversion

I would like to have some help on this since I've been spending hours to do it, but I couldn't. I want to write a function that takes signed integer and convert it to a dotted IP address using Intel standard algorithm, here is an example:

the IP address 192.168.18.188 displays as -1139627840. To convert this IP address using Intel standards, I will have to perform the following procedure:

  1. Convert (-1139627840) to a hex value. BC12A8C0.
  2. Reverse the hex bytes, as shown below: CO A8 12 BC
  3. Convert the bytes from hex to decimal, as shown below: 192 168 18 188
  4. The IP address displays in the following format: 192.168.18.188

Any help would be appreciated.

Upvotes: 0

Views: 1465

Answers (2)

Jed
Jed

Reputation: 10897

I know this doesn't answer your question in regards to the Intel Standard, but just to throw it out there (in case you're trying to reinvent the wheel), you can convert an int to an IP like this:

string ip = new IPAddress(BitConverter.GetBytes(-1139627840)).ToString();

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 599776

The magic is in combining:

  • the >> operator, which shifts the bits in a number to the right
  • the & operator, which does a bit-wise and (the more common && does a logical and)

So something like this:

var number = -1139627840;
var b1 = number & 255;
var b2 = (number >> 8) & 255;
var b3 = (number >> 16) & 255;
var b4 = (number >> 24) & 255;
Console.WriteLine(string.Format("{0}.{1}.{2}.{3}", b1, b2, b3, b4));

Upvotes: 1

Related Questions