开发者

byte array to a short

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?


For unsigned data:

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

For signed data:

val = ((data[2] << 8) & 0xff00) | (data[3] & 0xff);


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.


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));


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.


Simply iterate through the elements and do a Int.Parse

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜