How do display the Integer value of an IPAddress [closed] - c#

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 14 years ago.
Improve this question
I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.
However...
The number returned is NOT the true conversion.
e.g. For IP 58.0.0.0 , the System.Net namespace gives me a value of 58...
When in fact, the integer value should be 973078528
Can someone please show me the correct code do convert this?
The formula should be.. (for ip 192.1.20.10).
192 * (256*256*256) + 1 * (256*256) + 20 * (256) + 10
The reason this formula is correct is that the number it returns you can use in a >= and <= query to determine an IP address that falls within a range.
The Address Property (of the IPAddress instance) does not calculate/return this. A bonus point for anyone that knows why the address property does not return what I think is the correct answer...
Other examples from other links did not work either.

Please see How to convert an IPv4 address into a integer in C#?

What you are seeing appears to be an endian problem.
As a generic function, if your IP address is A.B.C.D then the value you're after is:
A << 24 + (= A * 16777216)
B << 16 + (= B * 65536)
C << 8 + (= C * 256)
D
On little endian machines when the four-byte array ABCD is cast into an integer it comes out with A as the least significant byte instead of the most significant.
I don't write vb.net code, but it should be pretty trivial to knock out a function that'll do this.
You'll need to ensure that A - D are all in the 0 .. 255 range first, though!

How to convert an IPv4 address into a integer in C#?
example code is listed in the picked answer
e; f, b

This might work, will try it and see.
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}

Related

Why does Console.WriteLine(3 + 'z' + 4); result in 129 in C#? [duplicate]

This question already has answers here:
char + char = int? Why?
(15 answers)
Closed 4 years ago.
This is something they included as part of my course, just wondering why it does this and what they were trying to show with it but can't seem to figure it out. Is it some sort of principle when trying to concatenate chars to numbers?
Am I right in assuming that 'z' is a char because it's in single quotes here?
Is it some sort of error because you shouldn't write stuff like this?
Thanks in advance!
z is char value, char is basically a number. z will be implicitly converted to int (z code is 122), that's why 3 + 'z' + 4 == 129. It will be converted to int because in statement 3 + 'z' 3 is int, so result of addition will be also int.
In C# char is a 16 bit numeric value which represents a unicode character. So in your case z is implicitly evaluated as 122. So 3 + 122 + 4 equals 129.

How to convert a base 10-number to 3-base in net (Special case)

I'm looking for a routine in C# that gives me the following output when putting in numbers:
0 - A
1 - B
2 - C
3 - AA
4 - AB
5 - AC
6 - BA
7 - BB
8 - BC
9 - CA
10 - CB
11 - CC
12 - AAA
13 - etc
I'm using letters, so that it's not so confusing with zero's.
I've seen other routines, but they will give me BA for the value of 3 and not AA.
Note: The other routines I found was Quickest way to convert a base 10 number to any base in .NET? and http://www.drdobbs.com/architecture-and-design/convert-from-long-to-any-number-base-in/228701167, but as I said, they would give me not exactly what I was looking for.
Converting between systems is basic programming task and logic doesn't differ from other systems (such as hexadecimal or binary). Please, find below code:
//here you choose what number should be used to convert, you wanted 3, so I assigned this value here
int systemNumber = 3;
//pick number to convert (you can feed text box value here)
int numberToParse = 5;
// Note below
numberToParse++;
string convertedNumber = "";
List<char> letters = new List<char>{ 'A', 'B', 'C' };
//basic algorithm for converting numbers between systems
while(numberToParse > 0)
{
// Note below
numberToParse--;
convertedNumber = letters[numberToParse % systemNumber] + convertedNumber;
//append corresponding letter to our "number"
numberToParse = (int)Math.Floor((decimal)numberToParse / systemNumber);
}
//show converted number
MessageBox.Show(convertedNumber);
NOTE: I didn't read carefully at first and got it wrong. I added to previous solution two lines marked with "Note below": incrementation and decrementation of parsed number. Decrementation enables A (which is zero, thus omitted at the beginning of numbers) to be treated as relevent leading digit. But this way, numbers that can be converted are shifted and begin with 1. To compensate that, we need to increment our number at the beginning.
Additionaly, if you want to use other systems like that, you have to expand list with letter. Now we have A, B and C, because you wanted system based on 3. In fact, you can always use full alphabet:
List<char> letters = new List<char> {'A','B','C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
and only change systemNumber.
Based on code from https://stackoverflow.com/a/182924 the following should work:
private string GetWeirdBase3Value(int input)
{
int dividend = input+1;
string output = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 3;
output = Convert.ToChar('A' + modulo).ToString() + output;
dividend = (int)((dividend - modulo) / 3);
}
return output;
}
The code should hopefully be pretty easy to read. It essentially iteratively calculates character by character until the dividend is reduced to 0.

conversion issue while converting [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i want to convert a character into an integer number for processing but it is not picking it
code
test = Convert.ToInt32(ch);
Console.WriteLine(test);
if (test >= 0 && test <= 9)
{
numst[num_count] = test;
Console.WriteLine(numst[num_count]);
num_count++;
}
test,num_count are integer,numst is a integer array and ch is a character
i want to check that if ch is a number then put it into the integer array
please help me about where i was wrong in logic
thank you
If ch is a numeric character then this doesn't do what you think it does:
Convert.ToInt32(ch);
For example, the integer value of the character '9' is 57. According to your if condition, the only characters you're expecting are essentially unprintable characters (NUL through TAB).
It sounds like you're looking for Char.GetNumericValue():
test = Char.GetNumericValue(ch);
If you want to test if a digit, use char.IsDigit(). To convert that character to an integer use char.GetNumericValue():
if (char.IsDigit(ch))
{
numst[num_count] = char.GetNumericValue(ch);
Console.WriteLine(numst[num_count]);
num_count++;
}
char.IsDigit() will return true for characters between '0' and '9', but false for e.g. '*'.
char.GetNumericValue() gives you the numeric value that was represented by the character. So a '9' is converted to 9.
Convert.ToInt32() instead converts the char's value to an int. The value of a character like '9' is 0x39 or 57.
there are 2 methods
1st method
if (char.IsDigit(ch))
{
numst[num_count] = char.GetNumericValue(ch);
Console.WriteLine(numst[num_count]);
num_count++;
}
2nd method
if (ch >= 48 && ch<=57)
{
numst[num_count] = char.GetNumericValue(ch);
Console.WriteLine(numst[num_count]);
num_count++;
}
both of them are working fine and have some results
thank you for every one help me

Converting a String to hex and calculate binary result in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I got stuck with my code, tried anything on this side and many other things Google showed.
To the problem:
I try to convert some code-snips from C# to phyton, but on this special point i got stuck.
public static long decode(string data, int size, int offset = 0)
{
long value = 0;
for (int i = 0; i < size; ++i) {
value <<= 6;
value |= (long)data[offset + i] - 0x30;
}
return value;
}
The String Data could be something like 1Dh. Based on this I convert each char to the hex-equivalent: 0x31, 0x44, 0x68 and subtract 0x30; so I get 0x1, 0x14, 0x38;
In the next step I have to convert to the binary equivalent 000001, 010100, 111000 and merge this to
000001010100111000. From this I want to get the integer meaning, in this case 5432.
Is there a possibility to do this in a smart and easy way in python?
It's actually pretty easy, and the translation is pretty straight forward. You can continue to use your bit shifting. The only change is the syntax of for-loop and using ord() to get the integer value from a character.
def decode(data, size, offset=0):
value = 0
for ch in data[offset:size]:
value <<= 6
value |= ord(ch) - 0x30
return value
Running this in the interpreter, I get 5432:
>>> decode("1Dh", 3)
5432

Comparing IPAddress (stored as varbinary)

I have an IPAddress column on my Activity table. This is stored as a varbinary(16) so that it can be efficient (moreso than storing as a string) and also support IPv6. When I store, I basically get the value of (new System.Net.IPAddress("127.0.0.1")).GetAddressBytes().
What I want to be able to do is search for all IP addresses that begin with certain bytes, e.g. "127.*". I can easily get the bytes for that, so just assume that I am able to get new byte[] { 127 }.
Given that, how can I actually write a LINQ to SQL query to get me the data I want?
Sadly, I don't have StartsWith, though I essentially want the equivalent of Activity.Where(a => a.IPAddress.StartsWith(new byte[] { 127 })).
A while ago, I had to find the location of a given IP. We got the IP from the request. There are free databases which gave us this mapping. In IPv4, when we say the IP as "a.b.c.d" it is essentially......
a * (256^3) + b * (256^2) + c * (256) + d
http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp
so when you say you want an IP address starting with "a", you are looking for IPs between a * 256^ 3 and a * 256^3 + 256 * (256^2) (b = 256) + 256 *(256) (c=256) + 256( d=256) (lower / upper limit may vary a little bit depending on whether you want to include/exclude the limits).
That said, there are specific IPs reserved for specific purposes(like 127.0.0.1 which is localhost, 0.0.0.0 cannot be an IP etc).
So your linq query would be
from i in iList where i >= MIN && i <= MAX select i;
where iList is your initial list
MIN is your min value for your range
MAX is your max value for your range
If the data is returned as a byte array, why not reference the first byte of the array? Sounds like;
Activity.Where(a => a.IpAddress[0] == 127);
might be what your looking for?
You could store the IP address as a hex string, where 127.0.0.1 = "7F000001" then if you want to find an IP address starting with 192.168.* you can use
Activity.Where(a => a.IpAddress.StartsWith("C0A8"));

Categories