qbytearray.at()到unsigned int

时间:2014-07-24 23:08:43

标签: c++ qt unsigned-integer static-cast qbytearray

好的我有一个关于将一个元素转换为QByteArray(应该是一个char吗?)到一个无符号整数的两部分问题。

这是我的代码:

QByteArray data_read_buffer;

unsigned int data_recieved_size = 0;

/* the code below is an external function that populates the QbyteArray. shouldn't be important putting only to show that I assign a value to the byteArray./*

readFromComPortSafe(data_read_buffer); 

data_recieved_size  = static_cast<unsigned int>((data_read_buffer.at(2)));

确定。所以我在data_recieved_size中返回的结果是错误的“每隔一段时间”我进入调试器,当我检查data_read_buffer的值时,我得到这个:

\ 000 \ 003 \ 203 \ 00 \ 205 ....(我们与变音符号有一些角色)

当我检查data_recieved_size的值时,我得到4294967171

所以我的第一个问题是这个

我是否在从char转换为unsigned int时出错了?

我的第二个问题是:

\ 203在qByteArray中代表什么?我想我不明白我在看什么。我的理解是char类型是unicode字符????我期待QByteArray中的第二个元素是0x83或131.这如何转换为\ 203?

如果有人能对这一点提供一些见解我会很感激。

由于

2 个答案:

答案 0 :(得分:1)

char可以签名或取消签名,具体取决于您的平台,在您签名的情况下。

考虑一下当您致电data_read_buffer.at并且返回值为-125时会发生什么:

  • -125 char0x83
  • 然后,此值会转换为int内的static_cast,即0xffffff83
  • static_cast现在将此值转换为unsigned int,这只是复制位(至少在两台补充机上)。
  • 0xffffff83 unsigned int为4,294,967,171

如果您想要转换为unsigned int并避免使用代码扩展,那么您需要执行类似

的操作
static_cast<unsigned int>(static_cast<unsigned char>(data_read_buffer.at(2)));

答案 1 :(得分:0)

char类型通常是签名的。虽然不是很明显,但您将其扩展为32位作为有符号值,然后将其重新解释为无符号值。如果您插入static_cast< unsigned char >,那么您将扩大无符号值。