ANSI C, char to hex conversion

Hi,

I have a

char buf[1024],ch;

and the buf is filled with the result from MySQL server which I get like this

numbytes = recv(sock, buf, 1024, 0));

I have the followingcode to display the results

printf("received %ld bytes:\n",numbytes);
    for(c=0;c<numbytes;c++){
        ch = (char)buf[c];
        printf("%c_",ch);
    }
    printf("\n\n");
    for(c=0;c<numbytes;c++){
        printf("%02X_",(int)*(buf+c));
    }
    printf("\n\n");
    for(c=0;c<numbytes;c++){
        printf("%c_",(int)*(buf+c));
    } 

and the output is like this:

received 65 bytes:
=____
_5_._0_._2_7_-_s_t_a_n_d_a_r_d______a_k_u_,_w_6_C_0__,_________________f_2_f_+_A_F_y_P_a_z_`_U__

3D_00_00_00_0A_35_2E_30_2E_32_37_2D_73_74_61_6E_64_61_72_64_00_FFFFFFAB_00_00_00_
61_6B_75_2C_77_36_43_30_00_2C_FFFFFFA2_08_02_00_00_00_00_00_00_00_00_00_00_00_00_
00_00_66_32_66_2B_41_46_79_50_61_7A_60_55_00_

61_0_0_0_10_53_46_48_46_50_55_45_115_116_97_110_100_97_114_100_0_-85_0_0_0_97_107_117_
44_119_54_67_48_0_44_-94_8_2_0_0_0_0_0_0_0_0_0_0_0_0_0_0_102_50_102_43_65_70_121_80_97_122_96_85_0_

so for some reason two bytes are converted into a negative integer or a huge hex number.

The right values must be just AB and A2... I'm totally lost here..
Can anyone please explain me why it happens so?

Thank you!

printf("%02X_",(int)*(buf+c));

Try casting it to unsigned. In an int, the high bit means negative if it is turned on. When you promote a char to a (signed) int, that high bit is extended all the way across to preserve the sign.

Oh.. thank you!