Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing unsigned short values

Tags:

c

  unsigned short a;
  char temp[] = "70000";
  a = atoi(temp);
  printf("a: %d\n", a);

Gives me the output a: 4464 when it should be a: 70000 Is there a better way to convert from ASCII to a decimal? The range of a unsigned short is 0 - 65535

like image 599
foo Avatar asked Feb 27 '11 17:02

foo


2 Answers

As schnaader said, you may be running into an overflow problem.

But answering your printf question about outputting unsigned values, you want the u modifier (for "unsigned"). In this case, as Jens points out below, you want %hu:

printf("a: %hu\n", a);

...although just %u (unsigned int, rather than unsigned short) would probably work as well, because the short will get promoted to int when it gets pushed on the stack for printf.

But again, that's only if the value 70000 will fit in an unsigned short on your platform.

like image 186
T.J. Crowder Avatar answered Oct 24 '22 06:10

T.J. Crowder


You are answering the question yourself. The range of a unsigned short is 0-65535, so 70000 doesn't fit into it (2 bytes), use a datatype with 4 bytes instead (unsigned int should work, you can check the size with sizeof).

like image 39
schnaader Avatar answered Oct 24 '22 05:10

schnaader