We help IT Professionals succeed at work.

char to unsigned int

meverest asked
Hi folks,

i have a string of char, and want to see the contents in decimal with this:

for(j=0;j<i;j++) printf("%d,", inbuf[j]);

but for 127 < inbuf[j] < 255, i get a signed int (expected), so how do i see the right value?

i try

for(j=0;j<i;j++) printf("%u,", inbuf[j]);

but i get incorrect (very big) value - i assume it represents the char as the high byte of an int maybe(?)

i have tried other combinations... any suggestions most appreciated.

regards,  Mike.

Watch Question

If you want the unsigned decimal number

            printf("%d,",      *(unsigned char *) (inbuf + j )   );

     unsigned char *p = inbuf;

     for(j=0;j<i;j++) printf("%d,", p[j]);

If you want the hex number

            printf("%2x,",      *(unsigned char *) (inbuf + j )   );

     unsigned char *p = inbuf;

     for(j=0;j<i;j++) printf("%2x,", p[j]);

AxterSenior Software Engineer

I think what you want is to print the number value of the charactor.

If so, then this is how you do it.
for(j=0;j<i;j++) printf("%c,", inbuf[j]);

Use %c instead of %d
Top Expert 2008


Hi axter,

well yes, but no - this array of char happens to be filled with non-printable data :(

(see my other question for the reason why)

take this as an example.  inbuf[2] contains a 16 bit integer read from a socket:

i = recv(sockCli, inbuf, sizeof(inbuf), 0))
printf("Size of response:\n int %d,%d\n", inbuf[0], inbuf[1]);
printf(" uint %u, %u\n", inbuf[0], inbuf[1]);
printf(" uchar %d,%d\n", *(unsigned char *) (inbuf),*(unsigned char *) (inbuf+1));
unsigned char *p = (unsigned char *) inbuf;
printf(" uchar %d,%d\n", p[0], p[1]);
printf(" hex %2x,%2x\n",  *(unsigned char *) (inbuf), *(unsigned char *) (inbuf + 1 )   );
printf(" uchar %2x,%2x\n", p[0], p[1]);

this code produces:

Size of response:
 int 0,-113
 uint 0, 4294967183
 uchar 0,143
 uchar 0,143
 hex  0,8f
 uchar  0,8f

so thienpnguyen's suggestions give me the answer i am after...

thanks folks! :)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.