如何将unsigned short转换为unsigned char并将值存储在字符串中

时间:2019-06-28 20:32:33

标签: c++ c++11

我正在尝试将无符号的short值转换为无符号的char类型并将结果存储在字符串中。然后再次将字符串转换回unsigned char以获取原始的unsigned short值。

我已将无符号的short值转换为字符串。如何使用unsigned char数组获取unsigned short值。请帮我解决这个问题

unsigned short a=1234;
 unsigned short b=5678;
 std::string str="";
 str+=std::to_string((unsigned char)a & 0xFF);
 str+=std::to_string((unsigned char)(a>>8)& 0xFF);
 str+=std::to_string((unsigned char)b & 0xFF);
 str+=std::to_string((unsigned char)(b>>8)& 0xFF);
 cout<<"String Value: "<<str<<endl;

预期输出为“ 12345678”,其中a = 1234 b = 5678;

1 个答案:

答案 0 :(得分:1)

除非被100除,否则您将无法从1,234中得到12。同样地,要从5,678中得到56,您需要被100除。您的代码不会被100除。所以我可以看不到为什么会在字符串中看到“ 12”或“ 56”。

1234的十进制是04D2的十六进制,与FF的十六进制进行与运算得到D2的十六进制或210的十进制。您为什么不希望字符串中出现“ 210”?

同样,要从1234获得12,您需要除以100。要从1234获得34,您需要mod100。因此,要获得预期的输出,您的代码应如下所示:

#include <iostream>

int main()
{
    unsigned short a=1234;
    unsigned short b=5678;
    std::string str="";
    str+=std::to_string((unsigned char)(a / 100));
    str+=std::to_string((unsigned char)(a % 100));
    str+=std::to_string((unsigned char)(b / 100));
    str+=std::to_string((unsigned char)(b % 100));
    std::cout<<"String Value: "<<str<<std::endl;
}
  

字符串值:12345678