Home > Enterprise >  Should i cast different?
Should i cast different?

Time:09-23

I have this C code(Is not for PC. Is 8bit microcontroller, CCS Compiler)

long SirenVolt;//unsigned int16
long long DummyVolt;//unsigned int32

DummyVolt=read_adc();//Function always get values from 0 to 1024
SirenVolt=(long long)((493*DummyVolt)/100);

The last line should be cast as long instead? I need that SirenVolt gets an unsigned int16(long, according the CCS Compiler) enter image description here

CodePudding user response:

Should i cast different?

Yes, SirenVolt is a long and you cast to a long long.

The default being unsigned and long being 16 bit is a bit confusing. It doesn't support unsigned int64 either.

From the chat:

read_adc() function returns an unsigned int16

And since it returns max 1024, this should work:

long SirenVolt = (long) (read_adc() * 493LL / 100);

If the compiler doesn't support LL:

static const long long mul = 493;
static const long long div = 100;

long SirenVolt = (long) (read_adc() * mul / div);

read_adc() * mul makes a long long, max 504832, divided by 100 max 5048, fits fine in an unsigned int16 (the long).

  • Related