# Thread: Convert int to two char

1. ## Convert int to two char

hi,
how can I covert a int to two char...
I have some idea using shift operators..
thanks...

2. Your idea is a good one - see what you can come up with

3. my idea:
Code:
```char is 1 byte, int is 2 byte
char a, b;

int someValue, result;
a = someValue;
b = someValue << 8;

result = getValue(a,b)

int getValue(char a, char b)
{
int value1, value2, total ;
value2 = value2 >> 8;
total = value2 + value1;
}```

4. Yes, that's the basic approach.
Now just put it all into a working program and see how you get on.

5. Originally Posted by redsar
my idea:

6. I have some idea using a union. That's the incredibly lazy way to do it.

Quzah.

7. Originally Posted by Emmanuel Delaha
Endianness has everything to do with how an int is stored in memory, and thus how you would cast a char to it.

Code:
```int someint = 0x01234567;
char somechar = (char)someint;```
On a little endian machine, somechar would equal 0x67. On a big endian machine, somechar would equal 0x01.

8. Originally Posted by bithub
Code:
```int someint = 0x01234567;
char somechar = (char)someint;```
On a little endian machine, somechar would equal 0x67. On a big endian machine, somechar would equal 0x01.
Of course, you meant

char somechar = (char)(someint & 0xFF);

because a char can have more than 8 bits. The actual value is defined in CHAR_BIT from <limits.h>. On the DSP I work with (TMS320C54) the value is 16.

9. What machine are you running this on that an int is only 2 chars?

Also, endianess does not affect shifting operations(*), so your code will yield the same result on both little and big endian machines. Casting is something different though.

(*) meaning sall, sarl, shrl or c's representations produce the same decimal results on both big and little endian

10. Originally Posted by Nyda
What machine are you running this on that an int is only 2 chars?
Many embedded systems are 16 bit, so he might be working on a DSP or a microcontroller. He might also be working on an old DOS or Windows 3.11 machine

11. You can first AND the number with 0xFFh into one variable and then again AND the original number with 0xFF0h into another var.