Save int in 2 characters

Quick question: since int is 2 bytes and char is 1 byte, I want to save the int variable in 2 char variables. (for example, bit 1-8 in the first char, bit 9-16 in the second char). Using C as a programming language.

How can i achieve this? There will be something like:

int i = 30543; char c1 = (char) i; char c2 = (char) (i>>8); 

do this job?

I could not find if int listing in char could just reset bit 9-16.

+6
source share
2 answers

This was extracted from c11 draft n1570

6.5.4 Role Operators

  1. If the value of the expression is presented with a larger range or accuracy than is required for the type called cast (6.3.1.8), then the cast sets the conversion even if the type of the expression matches the type and removes any additional range and accuracy.

Thus, the cast will really remove the extra bits, but it is still not necessary, because the value will be implicitly converted to char , and in any case, this applies.

+4
source

You just need to:

 char c1 = (char) ((i << 8) >> 8); char c2 = (char) (i >> 8); 
0
source

Source: https://habr.com/ru/post/987334/


All Articles