# short value to char

This is a discussion on short value to char within the C Programming forums, part of the General Programming Boards category; How i can convert a short value (example 120) to char? I must do it using bit shifting but how..?...

1. ## short value to char

How i can convert a short value (example 120) to char?
I must do it using bit shifting but how..?

2. I suppose you are not looking for something like this:
Code:
```short x = 120;
char y;

...
y = x;```
You may need to write:
Code:
`y = (char)x;`
if the compiler issues a warning for "loss of precision".

--
Mats

3. Thats not solve my problem. Decimal 120 is hex value 78.
I need to get first 8 bits in one char and last 8 bits to another char.
I just dont know how i have to shift those bits..

I hope you understand what i try to say

4. Assuming that sizeof(short) is 2, you can do this;
Code:
```#include <stdio.h>

typedef union
{
short short_value;
char char_value[2];
} Converter;

int main()
{
Converter c;
c.short_value = 120;

fprintf(stdout, "%d %d\n", x.char_value[0], x.char_value[1]);    /* print the two chars as int values */
}```
Note that the values output are machine dependent (they depend on endianness).

You can also do this via bit fiddling, or by manipulation of a pointer, but I'll leave that as a further exercise. The technique above will, at least, give the same values that you should obtain via bit fiddling.

5. Originally Posted by downfall80
I need to get first 8 bits in one char and last 8 bits to another char.
Why didn't you just say that in the first place? Read the bit-shifting FAQ. Shift by the number of bits in a byte. (Hint: CHAR_BIT)

Quzah.