Peter W
Peter W

Reputation: 361

Store int in 2 chars

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.

Upvotes: 6

Views: 246

Answers (2)

Romain Hirt
Romain Hirt

Reputation: 1

You just have to do:

char c1 = (char) ((i << 8) >> 8);

char c2 = (char) (i >> 8);

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

This was extracted from the c11 draft n1570

6.5.4 Cast operators

  1. 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.

Upvotes: 4

Related Questions