Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store int in 2 chars

Tags:

c

casting

char

int

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.

like image 400
Peter W Avatar asked May 16 '15 13:05

Peter W


People also ask

Can char store have 2 digit numbers?

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.

Can we store integer in char array?

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.

Can I use char to store numbers?

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.


1 Answers

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.

like image 166
Iharob Al Asimi Avatar answered Sep 30 '22 17:09

Iharob Al Asimi