|
-
December 19th, 2002, 04:19 AM
#1
conversion help
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
-
December 19th, 2002, 05:24 AM
#2
my_addr.sin_port = atoi(puerto);
-
December 19th, 2002, 06:04 AM
#3
What the fact that what I need is a short int, not an int?
Thanks
-
December 19th, 2002, 06:22 AM
#4
I mean, atoi converts to int, not to short int, right?
-
December 19th, 2002, 06:36 AM
#5
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 ?
-
December 19th, 2002, 06:39 AM
#6
-
December 19th, 2002, 06:43 AM
#7
In my opinion the problem is when *puerto<0 because you can not convert signed to unsigned.
-
December 19th, 2002, 06:50 AM
#8
Okay. *puerto will never be >0, so I guess there's no problem.
Thanks a whole lot!
-
December 19th, 2002, 06:10 PM
#9
Sorry, but you're all wrong!!!
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):
Code:
portnoStr = getenv("PORTNO");
my_addr.sin_port = htons(atoi(portnoStr));
That's it. Good luck.
-
December 20th, 2002, 04:17 AM
#10
The platform is really AIX.
Will byte order be a problem, then?
Thanks.
-- naradaji
-
December 21st, 2002, 05:05 PM
#11
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|