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.
No c is a char and can only store 1 byte. @Broman No. A byte is a unit of memory, a char is a type, capable of representing a character from the implementation's basic character set. The debugger isn't showing two numbers.
You can add the ASCII value of 0 to the value you want to store digit into the character array. For example if you want to store 0,1,...,9 into the character array A[10], you may use the following code. This works only if the integer you want to store is less than 10.
The CHAR data type stores any string of letters, numbers, and symbols. It can store single-byte and multibyte characters, based on the database locale. The CHARACTER data type is a synonym for CHAR.
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 (6.3.1.8), 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With