问题描述
大家好:
我有一个unsigned char数组(大小为4):
unsigned char array [4];
array [0] = 0x00;
array [1] = 0x00;
array [2] = 0x02;
array [3] = 0xe7;
我想将array []转换为整数。
0x00 0x00 0x02 0xe7 = 00000000 00000000 00000010 11100111 = 743
感谢任何帮助。
C没有'' t保证UCHAR_MAX< = UINT_MAX也不保证UINT_MAX是> = 0xFFFFFFFF
。但是如果
你可以保证数组中的值是< = 0xFF:
#define lengthof(a)(sizeof) (a)/ sizeof(a [0]))
const unsigned char array [4] = {0,0,0x02,0xe7};
unsigned long ui = 0;
unsigned long mult = 1;
/ *
看起来你想要大端转换。对于小的
endian,只需按正常顺序索引数组
* /
for(unsigned i = 0; i< 4; ++ i){
ui + = mult * array [lengthof(array)-1-i];
mult<< = 8;
}
断言(ui == 743);
否则用uint32_t和
uint8_t类型在stdint.h中,这可能就是你想要的。
C并不保证UCHAR_MAX< = UINT_MAX没有r是否保证UINT_MAX为> = 0xFFFFFFFF。但是,如果你可以保证数组中的值是< = 0xFF:
#define lengthof(a)(sizeof(a)/ sizeof(a [ 0]))
const unsigned char array [4] = {0,0,0x02,0xe7};
unsigned long ui = 0;
unsigned long mult = 1;
/ *
看起来你想要大端转换。对于小的
endian,只需按正常顺序索引数组
* /
< snip>
你不需要为小端做那个。无论是小b $ b还是大端,数组[0]总是0,
数组[1]总是0,
array [2]将始终为0x02,并且
array [3]将始终为0xe7。
Hi all:
I have an unsigned char array (size 4):
unsigned char array[4];
array[0] = 0x00;
array[1] = 0x00;
array[2] = 0x02;
array[3] = 0xe7;
I would like to convert array[] to an integer.
0x00 0x00 0x02 0xe7 = 00000000 00000000 00000010 11100111 = 743
Any help is appreciated.
C doesn''t guarantee that UCHAR_MAX <= UINT_MAX nor does it guarantee
that UINT_MAX is >= 0xFFFFFFFF. But here is something that will work if
you can guarantee the values in the array are <= 0xFF:
#define lengthof(a) (sizeof(a)/sizeof(a[0]))
const unsigned char array[4] = { 0, 0, 0x02, 0xe7 };
unsigned long ui = 0;
unsigned long mult = 1;
/*
it looks like you wanted big endian conversion. For little
endian, just index the array in the regular order
*/
for (unsigned i = 0; i < 4; ++i) {
ui += mult * array[lengthof(array)-1-i];
mult <<= 8;
}
assert(ui == 743);
Otherwise replace unsigned long and unsigned char with the uint32_t and
uint8_t types in stdint.h which is probably what you intended anyway.
C doesn''t guarantee that UCHAR_MAX <= UINT_MAX nor does it guarantee
that UINT_MAX is >= 0xFFFFFFFF. But here is something that will work if
you can guarantee the values in the array are <= 0xFF:
#define lengthof(a) (sizeof(a)/sizeof(a[0]))
const unsigned char array[4] = { 0, 0, 0x02, 0xe7 };
unsigned long ui = 0;
unsigned long mult = 1;
/*
it looks like you wanted big endian conversion. For little
endian, just index the array in the regular order
*/
<snip>
You don''t need to do that for little endian. Whether it is little
or big endian, array[0] will always be 0,
array[1] will always be 0,
array[2] will always be 0x02, and
array[3] will always be 0xe7.
这篇关于将unsigned char []转换为int的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!