如何将uint8_t放在char数组中?

时间:2012-07-03 19:06:33

标签: c++ types casting printf

我正在尝试使用串行通信将一些数据发送到设备:

void VcpBridge::write_speed(char address, int spd) {
    uint8_t speed = (uint8_t)(127);
    ROS_ERROR("VCP BRIDGE: Sending %u to %u", speed, address);
    char msg[8];
    char command = 0x55, size = 0x02, csum;
    csum = speed + 0x64 + address;
    sprintf(msg, "%c%c%c%c%c%c", command, address, speed, size, 0x64, csum);
    ROS_ERROR(msg);
    write(fd_, msg, 6);
}

ROS_ERROR此处与printf相同。

除非speed的值超过127,否则一切正常。然后它始终在其位置打印?,并且设备不会返回正确的信息。你知道如何正确地投射吗?我试过了%u,但程序崩溃了。

2 个答案:

答案 0 :(得分:2)

在您的示例中没有充分的理由使用sprintf。试试这个:

void VcpBridge::write_speed(char address, int spd) {
    uint8_t speed = (uint8_t)(127);
    ROS_ERROR("VCP BRIDGE: Sending %u to %u", speed, address);
    char command = 0x55, size = 0x02, csum;
    csum = speed + 0x64 + address;
    ROS_ERROR(msg);
    char msg[] = { command, address, speed, size, 0x64, csum};
    write(fd_, msg, sizeof msg);
}

答案 1 :(得分:0)

感谢您的回答,我可以找出解决问题的热点。不使用sprintf并使用unsigned int是kay。最后的代码是:

void VcpBridge::write_speed(char address,int spd){
  uint8_t speed = (uint8_t)(200);
  unsigned char command = 0x55, size=0x02, csum;
  csum=speed+0x64+address;
  unsigned char msg[8]= { command, address, speed, size, 0x64, csum };
  write( fd_, msg, 6);
}