Quick question: Since int is 2 bytes and char is 1 byte, I want to store an int variable in 2 char variables. (like bit 1 - 8 into the first char, bit 9-16 into second char). Using C as programming language.
How can I achieve that? Will something like:
int i = 30543;
char c1 = (char) i;
char c2 = (char) (i>>8);
do the job?
I couldn't find whether casting an int into a char will just drop the bits 9-16.
Best How To :
This was extracted from the c11 draft n1570
6.5.4 Cast operators
- If the value of the expression is represented with greater range or precision than required by the type named by the cast (18.104.22.168), then the cast specifies a conversion even if the type of the expression is the same as the named type and removes any extra range and precision.
So the cast will indeed remove the extra bits, but it's not needed anyway because the value will be implicitly converted to
char, and the above would apply anyway.