Click to See Complete Forum and Search --> : conversion help


naradaji
December 19th, 2002, 03:19 AM
I have the following piece of code:

*************

puerto = getenv("PUERTO");

my_addr.sin_port = (short int)*puerto;

***************


where getenv is a function that returns a pointer to a char, and my_addr.sin_port is an unsinged short int.
As you can see, the issue here is the conversion from
char* to unsigned short int.
I get no compiler error with the above code, but I'm not sure it'll work in run-time.
Even if I remove the cast conversion (short int), I get no compiler error, which seems suspicious.

What is the best way to perform this conversion?

Thanks a lot.

-- naradaji

Alex F
December 19th, 2002, 04:24 AM
my_addr.sin_port = atoi(puerto);

naradaji
December 19th, 2002, 05:04 AM
What the fact that what I need is a short int, not an int?

Thanks

naradaji
December 19th, 2002, 05:22 AM
I mean, atoi converts to int, not to short int, right?

Doctor Luz
December 19th, 2002, 05:36 AM
if you are converting from char tounsigned short int:

In my opinion I don't see any problem if char is >=0. I don't know how would be the conversion if char is <0, probably will return the maximum unsigned short int.

if you are converting from char to short int I don't see any problem.

It's not clear... What type is my_addr.sin_port ?

naradaji
December 19th, 2002, 05:39 AM
it's unsigned short int

Doctor Luz
December 19th, 2002, 05:43 AM
In my opinion the problem is when *puerto<0 because you can not convert signed to unsigned.

naradaji
December 19th, 2002, 05:50 AM
Okay. *puerto will never be >0, so I guess there's no problem.
Thanks a whole lot!

j0nas
December 19th, 2002, 05:10 PM
Sorry, but you're all wrong!!! :D :D

Wrong byte-order is the problem (assuming Intel/AMD PC platform).

The socket API (winsocket or BSD sockets) uses network-byte order (which happens to be big endian). On Intel (which is little endian) platforms, you must convert values like short:s and int:s. And to be really portable, you should always use the network-to-host and host-to-network conversion routines provided by the socket API.

The conversion function in this case is host-to-netwrok-short: ntons(). Like this (together with atoi):

portnoStr = getenv("PORTNO");
my_addr.sin_port = htons(atoi(portnoStr));

That's it. Good luck.

naradaji
December 20th, 2002, 03:17 AM
The platform is really AIX.
Will byte order be a problem, then?

Thanks.

-- naradaji

j0nas
December 21st, 2002, 04:05 PM
Originally posted by naradaji
The platform is really AIX.
Will byte order be a problem, then?

Thanks.

-- naradaji


I don't know if AIX big or little endian, but as I said in my previous post: Do always use the socket API conversion routines.

Do like I showed you in my sample code. That will always be platform independent.