# Chary array of 4 to Int

• 07-20-2005
Coder87C
Chary array of 4 to Int
Hi, I have a chary array of

Code:

`chararray[4] = {B4,F1,C3,45};`
I want to change that to the int 45C3F1B4. I know that with MAKEWORD I can do 2 of them, but in this case I got 4, is there a macro for 4?
• 07-20-2005
kuphryn
One solution is via bitwise operators. You'll need to do stuff like shifting, AND, and OR.

Kuphryn
• 07-20-2005
Rashakil Fol
One good way is:

Code:

`(*chararray + (chararray[1] << CHAR_BIT) + (chararray[2] << (2 * CHAR_BIT)) + (chararray[3] << (3 * CHAR_BIT)))`
Code:

`(*((long *) chararray))`
This way's bad because it assumes little-endian order, and that's definitely an assumption you should not be making. But it's there.
• 07-20-2005
mrafcho001
i got a better way!!! (well different way)..

cast the char to an int and asign it to an int.. then since the numbers begin from 48 (0) to 57(9)(On the ASCII thing) all you do is subtract 48 from the int where the number has been assigned..
but you say... well thats only 1 digit..
multiply the number by 10 and do the same thing again but this time with the 2nd char in the array.

aint i a genius?
• 07-20-2005
quzah
Actually that's a crappy way to do it. There's nothing in the standard that states that zero has to have the decimal value of 48. Furthermore, since it is in fact a char going to an int, there is no need to cast it. It'll automaticly be promoted.

Hm... Actually, it depends on what the origional poster was talking about. If they have four bytes, that regardless of their value, are to be used to assemble a four byte integer, then no, it wouldn't work anyway.

However, if each byte in the array were to represent a single digit in a new number, which is only four digits long, it would work. Then, if this were the case, to make it more portable, you'd simply replace the value 48 which you used, with the '0' character. Like so:
Code:

```#include<iostream> int main() {     char array[] = { '1', '2', '3', '4' };     int number;     for( int x = number = 0; x < 4; x++ )     {         number *= 10;         number += array[ x ] - '0';     }     std::cout << number << std::endl;     return 0; }```
[/edit]

Of course you could have fun with unions...
Code:

```union foo {     int bar;     unsigned char bytes[ sizeof( int ) ]; };```
Or memcpy...
Code:

`memcpy( &myint, myarray, sizeof( int ) );`
Quzah.
• 07-20-2005
Rashakil Fol
Quote:

Originally Posted by mrafcho001
aint i a genius?

No. You could try actually reading the question.