Simple typecasting question

How's it going?

I have a hopefully-simple scenario involving typecasting.

Here's what I have:

double input = myCooler.getInput();
int conversion = (int)input;
uint8_t conv = (uint8_t)conversion;
SPDR = conv;

myCooler.getInput() is just a function that returns a double.

The SPDR register on my Arduino holds unsigned 8 bit integers at the minimum (and, conveniently, is all I need for my project.)

Can I write the above code like this instead, or is it bad practice? (Mind you, I don't need those variables after that chunk of code executes.)

SPDR = (uint8_t)((int)myCooler.getInput());

,sknahT

ynohtnA

You can say "SPDR = myCooler.getInput();" and the compiler will do the conversion for you. You need to use casting only when the default conversions won't work. When you assign a 'double' to a 'byte' the 'double' gets converted to 'int', then truncated to 'char' then cast to 'byte' (unsigned char).

I found this very interesting, short but to the point :

https://learn.sparkfun.com/tutorials/data-types-in-arduino

Interesting, so just to clarify, with your suggestion, 4.84 becomes 00000100 ?

To add on, there is a scenario where I need to discern what I initially wrote about ‘getting the input’ from another type of input. I do this by adding 64 to the value of the input, so the master on the receiving end of the transfer can know the difference between incoming data.

So, ( myCooler.getInput() + 64 ) becomes 01000100, correct?

Try it out in a simple test sketch. What happens?

If you store 4.84 in an integer type you will get the value 4.

If you store the expression 4.84 + 64 in an integer type you will get the value 68.

You could simply say:

uint8_t input = (uint8_t)myCooler.getInput();

And cut the extra steps in between.

Power_Broker:
You could simply say:

uint8_t input = (uint8_t)myCooler.getInput();

And cut the extra steps in between.

Yes, however it has been suggested that you can cut that out and say:

uint8_t input = myCooler.getInput();

But the question should be asked, why does myCooler.getInput() return a double? If it ever does return values over 255, any of these casts could result in a hidden bug. A major advantage of a cast is that it is explicit.

lennon-pledge:
Interesting, so just to clarify, with your suggestion, 4.84 becomes 00000100

No, 4.84 does not become 64 (which is what the octal constant 00000100 represents), it becomes 0b0100,.or more simply 4