Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 以正确的方式读取2个字节_C - Fatal编程技术网

C 以正确的方式读取2个字节

C 以正确的方式读取2个字节,c,C,我有一个传感器,它以这种方式传送16位:1。MSB 2。LSB: 这些值在此范围内: 0xffff ===> -32767 MIN 0x8000 ====> -1 LSB say -1 0x0000 ====> +1 LSB say 1 0x7FFF ====> 32767 MAX 我试图以可读的方式显示这些值。为此,我编写了一个小程序: #include <stdio.h> #include <math.h> #include &l

我有一个传感器,它以这种方式传送16位:1。MSB 2。LSB:

这些值在此范围内:

0xffff ===> -32767   MIN 
0x8000 ====> -1 LSB say -1 
0x0000 ====> +1 LSB say 1 
0x7FFF ====> 32767 MAX 
我试图以可读的方式显示这些值。为此,我编写了一个小程序:

#include <stdio.h>
#include <math.h>
#include <stdint.h>
int main(){
  char msbyte =0x7f;
  char lsbyte = 0xff;
  int16_t temp=0;
  temp = (msbyte<<8) | lsbyte;
  printf(" %4x temp %d ", temp,temp);

  return 0 ;

}
#包括
#包括
#包括
int main(){
char msbyte=0x7f;
字符lsbyte=0xff;
int16温度=0;
temp=(msbyte使用以下各项:

uint8_t msbyte =0x7f;
uint8_t lsbyte = 0xff;
如果
char
在您的实现中表现为
signed char
,则在oring时lsbyte将扩展符号位,结果可能是意外的。要解决此问题,应使用
unsigned char
uint8\t

尽管如此,输出范围将为:

0xffff ===> -1 
0x8000 ====> -32768
0x0000 ====> +1 LSB say 1 
0x7FFF ====> 32767 MAX 
如果确实需要指定的范围,请执行以下操作:(保持msbyte和lsbyte
无符号

int16\t num16=0;
温度=(mByte变化:

char msbyte =0x7f;
char lsbyte = 0xff;

char
是实现中的签名类型,当升级到
int
时会进行签名扩展

也改变了:

printf(" %4x temp %d ", temp,temp);


要避免在
temp
为负时进行有符号扩展。

如前所述,您的问题是高位被用作符号位

您可以使用以下方法避免此问题:

uint8_t msbyte =0x7f;
uint8_t lsbyte = 0xff;
uint16_t temp=0;
此外,我发现在处理嵌入式/设备数据时使用非常有用

例如,定义:

typedef unsigned char BYTE
typedef unsigned int WORD

并在代码中使用字节和单词。

您的数据类型
char
(带符号)和格式代码
%d
(带符号)定义您的值是被解释为有符号整数还是无符号整数。答案中有更多详细信息。首选
“%”PRId16
要打印
int16\u t
LSB
MSB
平均
最低有效位
最高有效位
,请不要发明自己的语言…你确定要签名结果吗?@specializet-虽然不太常见,
LSB
MSB
,但肯定被Wikipedia同意:最小值应该是-32768=0xffffI如果这对你有帮助,我很高兴。我希望你理解为什么你需要未签名。我理解了未签名的,但我仍在尝试REST。不需要在转换之前进行转换?他也使用了错误的格式打印specifier@Giorgi您可以在切换时看到整型升级为了理解为什么不需要强制转换。正确的打印方式是:
printf(“%4x temp%”“PRId16”\n),(unsigned int)temp,temp);
我使用C99标准头
来表示可移植大小的注释基元类型,例如
uint8\u t
和相应的
uint8\u MAX
等。
printf(" %4x temp %d ", (uint16_t) temp,temp);
uint8_t msbyte =0x7f;
uint8_t lsbyte = 0xff;
uint16_t temp=0;
typedef unsigned char BYTE
typedef unsigned int WORD