Hi, I have a chary array of
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?Code:chararray[4] = {B4,F1,C3,45};
Hi, I have a chary array of
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?Code:chararray[4] = {B4,F1,C3,45};
One solution is via bitwise operators. You'll need to do stuff like shifting, AND, and OR.
Kuphryn
One good way is:
One bad way is:Code:(*chararray + (chararray[1] << CHAR_BIT) + (chararray[2] << (2 * CHAR_BIT)) + (chararray[3] << (3 * CHAR_BIT)))
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.Code:(*((long *) chararray))
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?
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.
[edit]
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:
[/edit]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; }
Of course you could have fun with unions...
Or memcpy...Code:union foo { int bar; unsigned char bytes[ sizeof( int ) ]; };Quzah.Code:memcpy( &myint, myarray, sizeof( int ) );
Last edited by quzah; 07-20-2005 at 09:03 PM.
Hope is the first step on the road to disappointment.
No. You could try actually reading the question.Originally Posted by mrafcho001