Hi i am trying to concatinate 4 integers one integer. I used the concatinate function found here :
https://stackoverflow.com/a/12700533/2016977
My code:
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
void stringtoint(){
struct router *ptr;
ptr=start;
while(ptr!=NULL){
int a;
int b;
int c;
int d;
sscanf(ptr->ip, "%d.%d.%d.%d", &a, &b, &c, &d);
int num1 = concatenate(a,b);
int num2 = concatenate(c,d);
int num3 = concatenate(num1,num2);
printf("%d\n",num3);
ptr=ptr->next;
};
}
The problem:
I am dealing with IP address numbers e.g. 198.32.141.140 i am breaking them down to 4 integers and concatenate them to form 19832141140, however my concatenate function is doing maths on the larger number like 198.32.141.140 (becomes) - >-1642695340
but it is concatenating the IP which are small numbers e.g. 164.78.104.1 becomes 164781041 (which is correct)
How should i solve the problem, basically i am trying to make a string of IP e.g. 198.32.141.140 into an integer number 19832141140
Your proposed approach is likely a very big mistake. How do you distinguish 127.0.1.1 from 127.0.0.11?
It's much better to treat IP addresses as exactly what they are. Namely, a.b.c.d represents
a * 256^3 + b * 256^2 + c * 256^1 + d * 256^0
and done in this way you can not possibly run into the issue I just described. Moreover, the implementation is trivial:
unsigned int number;
number = (a << 24) + (b << 16) + (c << 8) + d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With