两个unsigned char 转short,short转两个进制char

1. 位运算

short value=200;
char c = (value>>8)&0xff;//取高字节
char d = value& 0xff;//取低字节

将高位字节移位至short的高八位中,低字节赋值到short的低八位中。

#include <iostream>
using namespace std;
 
int main()
{
    unsigned char a[2] = {0x55, 0xff};
    short result;
    result = result | a[1]; // 小端模式
    result = result << 8;
    result = result | a[0];
    
    cout << result << endl; // -171
    return 0;
}

2. 联合体

#include <iostream>
using namespace std;
 
union TwoByte
{
    short _short;
    unsigned char _uchar[2];
};
 
int main()
{
    unsigned char a[2] = {0x55, 0xff};
    TwoByte two_byte;
    two_byte._uchar[0] = a[0]; // 小端模式
    two_byte._uchar[1] = a[1];
    
    short result = two_byte._short;
    cout << result << endl; // -171
    return 0;
}

3.指针

#include <iostream>
using namespace std;
 
int main()
{
    unsigned char a[2] = {0x55, 0xff};
    short result;
    
    result = *((short *)a); // 小端模式
    cout << result << endl; // -171
    return 0;
}

 

场景:取字符串长度转为两个16进制char,使用QByteArray补足0

int len=msg.size();
QString sMsgLen=QString("%1").arg(len,4,16,QLatinChar('0'));
QByteArray lenArray;
lenArray=QByteArray::fromHex(sMsgLen.toLocal8Bit());
char lenL=lenArray.at(1);
char lenH=lenArray.at(0);

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值