tags:

views:

49

answers:

5

Hello,

I have an integer val.

data[0]=0;
data[1]=0;
data[2]=(val>>8)%256;
data[3]=val%256;

How do I do the oposite? How do I take the int from the char array?

+3  A: 

For unsigned data:

val = (data[2] << 8) | data[3];

For signed data:

val = ((data[2] << 8) & 0xff00) | (data[3] & 0xff);
Amardeep
this looks like the correct answer but it doesn't work
cateof
Can you give us the exact data types of `data` and `val`? You might be suffering from sign extension.
Amardeep
@Amardeep, Yup; that's my guess too. If `data` is `signed char *`, and either of `data[2]` or `data[3]` is greater than 127, the upper bits of the result may be filled with 1's.
strager
@strager maybe you are right. It seems that I am expecting a value ~185 here. How do I resolve the issue?
cateof
@cateof- Use `unsigned char` for `data`, or better yet `uint8_t`.
bta
A: 

Simply iterate through the elements and do a Int.Parse

`Int.Parse` isn't standard C, nor does it solve the problem here.
bta
A: 

Easy way:

int myint = mybyte[0]<<24+mybyte[1]<<16+mybyte[2]<<8+mybyte[3];

Assuming that's your bit order, and they're all unsigned. You may have to cast the bytes into ints in order to make sure they don't wrap (11001100 -> 11001100,0000000 instead of 11001100).

A far stranger way (though probably faster) would be something questionable legal with pointers:

int * myintp= mybyte;
int myint = *myintp;

I've not tested this at all, but it should theoretically work, assuming that the lengths work out, etc. It's still probably not a good idea.

zebediah49
Your pointer casting won't turn out well on a little-endian machine.
advait
how do I case the bytes into ints in order to make sure they don't wrap?
cateof
zebediah49
A: 

mod is a pretty expensive operation, particularly for saving a 32-bit int. You probably just want to memcpy. If you're worried about portability throw in a htonl:

#include<string.h>

uint32_t x = 12;
char data[4];
memcpy(data, &x, sizeof(x)); 

To go the other way you can just reverse it:

memcpy(&x, data, sizeof(x));
Paul Rubel
A: 

You could always try a union:

typedef union {
    int      i;
    uint8_t  bytes[sizeof(int)];
} int_u;

You can use this to turn an int into bytes or vice versa. Be mindful of endian-ness issues, however, if you are using this to transport data between platforms.

bta