user1604121
user1604121

Reputation: 43

Converting signed to unsigned integer in C

I am trying to combine two 8-bit number to an unsigned int but no matter what type casting I use, the result is still signed number. The code is complied using CodeWarrior 10.1 for freescale micro processor MC9S08LH64.

Things I tried that did not work - shift and add the two 8bits number then type cast them to be unsigned int at every step. - union/struct to combine the two 8-bit type cast them and the result number to unsigned int. - use unsigned int pointer (code below)

unsigned int acquire_sensor_voltage_internal_adc()
{ //this is internal ADC
     unsigned int result;
     unsigned int* data_ptr;
     char print_buffer [50];
     int_convert cvt;
    //internal adc collecting counts of input voltage
    //______________________________________________

    //writing to ADCSC1A initiate the conversion sequence
    ADCSC1A= 0x09;
    while(!ADCSC1A_COCOA){}

    cvt.parts.p0 = ADCRHA;
    cvt.parts.p1 = ADCRLA;
    data_ptr = &cvt.int_number;
    result = (unsigned int)*data_ptr;

    sprintf(print_buffer,"here!!!>>>>>>>%d\r\n",result);
    serial_sendString(print_buffer,strlen(print_buffer));
    //_______________________________________________
    return (unsigned int) result;
}

//definition of int_convert from.h file
typedef union{
unsigned int int_number;
struct{
    unsigned char p0;
    unsigned char p1;
}parts;
}int_convert;

Upvotes: 3

Views: 2813

Answers (4)

Lundin
Lundin

Reputation: 213306

You don't need to over-complicate things. This will work on any HC08:

unsigned int ADC_result = *(unsigned int*) &ADCRHA;

The HC08 architecture guarantees that the two reads to the ADC are in sync, it uses internal hardware buffers to save the lower byte as soon as the higher is read.

Upvotes: 0

You are printing result as a signed integer, because you use the %d format for printf. Use %u to indicate an unsigned integer (or %x if you want a hexadecimal printout).

sprintf(print_buffer, "here!!!>>>>>>>%u\r\n", result);

By the way, it would probably be a good idea to use bitwise operations rather than a union to convert the two bytes to a single unsigned int. That way your code would be more portable to other compilers where unsigned is more than two bytes. Assuming that the L and H in ADCRLA and ADCRHA mean “low” and “high”:

result = (ADCRHA << 8) & ADCRLA;

Upvotes: 0

Jens Gustedt
Jens Gustedt

Reputation: 78903

If you want to see an unsigned, you'd have to use an unsigned format to print that value. %d is not the correct format for that. Use %u and you will see it as unsigned.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182619

You could try:

result = ((unsigned)ADCRHA) << 8 | (unsigned)ADCRHB;

And then use the correct format specifier %u instead of %d.

Upvotes: 3

Related Questions