[英]Converting unsigned char array to signed short in C
I want to convert an array of unsigned char to a signed int!我想将一个无符号字符数组转换为有符号整数! I've already done some try, and the conversion works for the single element like this:
我已经做了一些尝试,转换适用于这样的单个元素:
unsigned char byte[2];
signed char *valueS[2];
byte[0] = 0b11110111;
byte[1] = 0b00001001;
//Conversion
for(int i = 0; i < 2; i++)
{
valueS[i] = (signed char*)&byte[i];
}
//Result
printf("Val 0 -> %d \n", *valueS[0]); // print -9 Correctly
printf("Val 1 -> %d \n", *valueS[1]); // print 9 Correctly
//But when i try to print a 16 bit signed
printf("Int %d \n", *(signed short*)valueS); //It doesn't work! I expected -2295
How can i get the 16 bit signed int from that unsigned char array?我怎样才能从那个无符号字符数组中得到 16 位有符号整数? Thank you in advance!
先感谢您!
How can i get the 16 bit signed int from that unsigned char array?
我怎样才能从那个无符号字符数组中得到 16 位有符号整数?
Supposing you mean you want to obtain the int16_t
whose representation is byte-for-byte identical to the contents of an arbitrary array of two unsigned char
, the only conforming approach is to declare an int16_t
object and copy the array elements to its representation.假设您的意思是要获得
int16_t
其表示形式与两个unsigned char
的任意数组的内容逐字节相同,唯一符合要求的方法是声明一个int16_t
对象并将数组元素复制到其表示形式。 You could use the memcpy()
function to do the copying, or you could do it manually.您可以使用
memcpy()
函数进行复制,也可以手动进行。
For example,例如,
#include <stdint.h>
// ...
unsigned char byte[2] = { 0xF7, 0x05 };
int16_t my_int;
unsigned char *ip = (unsigned char *) &my_int;
ip[0] = byte[0];
ip[1] = byte[1];
printf("Int %d \n", my_int);
You might see a recommendation to use a pointer aliasing trick to try to reinterpret the bytes of the array directly as the representation of an integer.您可能会看到建议使用指针别名技巧来尝试将数组的字节直接重新解释为整数的表示。 That would take a form similar to your code example, but such an approach is non-conforming, and formally it yields undefined behavior.
这将采用类似于您的代码示例的形式,但这种方法是不符合标准的,并且在形式上它会产生未定义的行为。 You may access the representation of an object of any type via a pointer to [
unsigned
] char
, as the code in this answer does, but, generally, you may not otherwise access an object via a pointer to a type incompatible with that object's.您可以通过指向 [
unsigned
] char
的指针访问任何类型对象的表示,正如本答案中的代码所做的那样,但通常,您可能无法通过指向与该对象不兼容的类型的指针访问对象。
Note also that the printf
above is a bit sloppy.还要注意,上面的
printf
有点草率。 In the event that int16_t
is a different type from int
, such as short int
, the corresponding printf
directive for it will have a length modifier in it -- likely %hd
.如果
int16_t
是与int
不同的类型,例如short int
,则相应的printf
指令中将包含长度修饰符——可能是%hd
。 But because of details of the way printf
is declared, it is the result of promoting my_int
to int
that will be passed to printf
.但是由于
printf
声明方式的细节,将my_int
为int
结果将传递给printf
。 That rescues the mismatch, and in practice, the printed result will be the same as if you used the correct directive.这样可以避免不匹配,并且在实践中,打印的结果将与您使用正确的指令相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.