How i can convert a short value (example 120) to char?
I must do it using bit shifting but how..?
How i can convert a short value (example 120) to char?
I must do it using bit shifting but how..?
I suppose you are not looking for something like this:
You may need to write:Code:short x = 120; char y; ... y = x;
if the compiler issues a warning for "loss of precision".Code:y = (char)x;
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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
Assuming that sizeof(short) is 2, you can do this;
Note that the values output are machine dependent (they depend on endianness).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 */ }
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.
Last edited by grumpy; 06-03-2009 at 03:20 AM.