Question

I have an unsigned char array, such as Data[2]. I needed it to compare with an output of a function returning unsigned int.

i tried to cast the Data[2] into unsigned int and vice versa. It didn't work.

What I am trying to do is:

if (Data[2] == ReadFlash2(40))
{
    //Do Something.
}

ReadFlash2 is a function returning unsigned int, while Data[2] is a unsigned char.

I tried to cast each of them, but it didn't work.

Is there something I am doing wrong? Which one should I cast, and to what should I cast it?

Thanks.

Edit: the code for the Readflash function:

unsigned int ReadFlash2(unsigned int Addr) // use as Read Function 
{
pMem = (unsigned int*)MEM_STR_ADR; 
pMem += Addr; 
Nop(); 
return(*pMem); 
}
Was it helpful?

Solution 2

It appears that you are accessing volatile memory on the microcontroller, and this could be causing some confusion when debugging. Try storing Data[2] and ReadFlash(40) into variables before the comparison:

unsigned char data_2 = Data[2];
unsigned int readflash2_40 = ReadFlash2(40);

if (data_2 == readflash2_40)
{
    //Do Something.
}

Now you should be able to inspect the actual values that are being compared by looking at the values in the variables.

OTHER TIPS

You shouldn't need to cast them at all, the rules in C relating to implicit promotions should take care of that for you.

In other words, comparing an unsigned char to an unsigned int will first promote the unsigned char to be compatible, then do the comparison.

It's all covered in C99 6.3.1.8 Usual arithmetic conversions which states (after discussing floating point types):

Otherwise, the integer promotions are performed on both operands.

Then the following rules are applied to the promoted operands:

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

... and so on, but that last paragraph above is the applicable one.

If the types are as you've stated and Data[2] actually is the same value as what's returned from ReadFlash2(40), then it's not a C environment, at least not according to the standard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top