【问题标题】:Conversion of binary encoded unsigned char to integer将二进制编码的无符号字符转换为整数
【发布时间】:2017-08-09 18:59:04
【问题描述】:

接下来,我将二进制数字 15 编码为 un​​signed char,然后将其转换为 int。但是,当我用 int8_t 替换 int 时,它不再输出 15。我不明白为什么。 int8_t的大小不是8位吗,所以应该和char匹配得很好,也是8位?

#include <iostream>
#include <string.h>

int main()
{

  unsigned char binValue = 0<<7 | 0<<6 | 0<<5 | 0<<4 | 1<<3 | 1<<2 | 1<<1 | 1<<0; // this is 15 in binary

  int intValue  = (int)binValue;

  // memcpy(&intValue,&binValue,sizeof(int)); // Or this one

  std::cout << intValue << std::endl;

  return 0;
}

【问题讨论】:

  • int8_t 已签名。试试uint8_t。 “停止工作”是什么意思?
  • 顺便说一句,这看起来很像 C++
  • @Jean-FrançoisFabre 对不起。我的意思是输出不再是预期的 15。程序仍然编译并运行。

标签: c++ binary char


【解决方案1】:

你看到的(实际上你没有看到的)是cout,当用int8_t 输入时,将值解释为一个字符,而 ASCII 代码 15 可能不会在调试控制台上留下任何可见的东西.请注意,环境(例如我的)可能会定义 int8_t 如下:

// _int8_t.h:
#ifndef _INT8_T
#define _INT8_T
typedef __signed char       int8_t;
#endif /* _INT8_T */

例如,如果您将binValue 更改为47,那么您会看到'/'。 要将字符类型(或int8_t)打印为十进制,请在打印过程中将其转换为int:

int main()
{
    unsigned char binValue = 0<<7 | 0<<6 | 1<<5 | 0<<4 | 1<<3 | 1<<2 | 1<<1 | 1<<0;
    // changed to 47 for demonstration purpose

    int8_t intValue  = (int8_t)binValue;

    std::cout << "as char:" << intValue << std::endl;
    std::cout << "as decimal:" << (int)intValue << std::endl;
    std::cout << "as decimal:" << +intValue << std::endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多