【问题标题】:Converting element in char array to int将char数组中的元素转换为int
【发布时间】:2014-09-12 03:52:37
【问题描述】:

我有一个 80 元素 char 数组,我正在尝试将特定元素添加到 integer 并且遇到一些数字错误。 十六进制数组元素 40 是 0xC0。当我尝试将其分配给 integer 时,我得到了十六进制 0xFFFFC0,但我不知道为什么。

char tempArray[80]; //Read in from file, with element 40 as 0xC0
int tempInt = (int)tempArray[40]; //Output as 0xFFFFC0 instead of 0x0000C0

【问题讨论】:

  • 因为0XC0char 中为负数,并且演员将符号保留为int
  • int tempInt = (int)tempArray[40]; --> unsigned tempInt = (unsigned)tempArray[40]; 可以解决问题。

标签: c++ arrays char


【解决方案1】:

之所以如此,是因为char 被视为已签名数字,而升级为int 会保留该符号。将数组从 char 更改为 unsigned char 以避免它。

【讨论】:

    【解决方案2】:

    因为0XC0char 中是负数,并且演员将符号保留为int。如果您想保持直接二进制转换或作为纯正值,您应该使用unsigned char

    【讨论】:

      【解决方案3】:

      根据您的实现,C++ 中的char 类型要么signed 类型unsigned 类型。 (C++ 标准要求实现选择任一方案)。

      为了安全起见,请在您的情况下使用unsigned char

      【讨论】:

      • 为你投票,我忘了它可能依赖于平台。
      【解决方案4】:

      为了更方便,我总是在声明和强制转换之前使用unsignedsigned。您可以编写以下内容:

      unsigned char tempArray[80]; //Read in from file, with element 40 as 0xC0
      unsigned int tempInt = (unsigned int)tempArray[40]; //Output as 0xFFFFC0 instead of 0x0000C0
      

      【讨论】:

      • 你的演员是不必要的,输出是 0xC0 而不是 0xFFFFC0
      • 很可能。但是这种类型的转换使代码更具可读性。
      【解决方案5】:

      char 可能是有符号的,因此从负的char 值转换将产生负的int 值,通常用二进制补码表示,从而产生非常高的二进制表示。

      改为使用 int tempInt = 0xFF & tempArray[40],将 tempArray 定义为 unsigned char,或转换为 unsigned char : int tempInt = (unsigned char)tempArray[40](不确定这是否是已定义的行为)。

      【讨论】:

        猜你喜欢
        • 2017-02-17
        • 2013-10-16
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        相关资源
        最近更新 更多