gpt4 book ai didi

c++ - 将二进制编码的 unsigned char 转换为整数

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:33 27 4
gpt4 key购买 nike

下面我把二进制的15编码成unsigned char,再转成int。但是,当我用 int8_t 替换 int 时,它不再输出 15。我不明白为什么。 int8_t 的大小不是 8 位,所以它应该与同样是 8 位的 char 匹配得很好吗?

#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;
}

最佳答案

您看到的(实际上是您看不到的)是 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;
}

关于c++ - 将二进制编码的 unsigned char 转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45598689/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com