【问题标题】:signed short to byte in c++在 C++ 中对字节进行签名短
【发布时间】:2012-05-04 12:16:04
【问题描述】:

我正在尝试使用 C++ 将 HEX 数字转换为短(2 字节) 一切都很好,除了一件事......从短到字节的签名转换(最后测试)

我发现了这个问题并不能真正从中受益:portable signed/unsigned byte cast,C++

这是我的测试:

// test 1 - positive B2Short (success)
byte *b = new byte[2];
b[0] = 0x10; //low byte
b[1] = 0x00; //heigh byte

signed short test = 0;
test = ByteToShort(b);
cout << test << endl;

// test 2 - negative B2Short (success)
b[0] = 0xF0; //low byte
b[1] = 0xFF; //heigh byte

test = 0;
test = ByteToShort(b);
cout << test << endl;

// test 3 - positive Short2B (success)
signed short n = 11;
ShortToByte(n, b);
test = ByteToShort(b);  // for display to see if it worked
cout << test << endl;

// test 4 - negative Short2B (FAIL!)
n = -11;
ShortToByte(n, b);
test = ByteToShort(b);  // for display to see if it worked
cout << test << endl;

使用的功能:

signed short ByteToShort(byte* bytes){

    signed short result = 0;
    result = (result<<8) + bytes[1]; // heigh byte
    result = (result<<8) + bytes[0]; // low byte
    return result;
}

void ShortToByte(signed short num, byte* bytes){

    bytes[1] = num & 0xFF00; // heigh byte
    bytes[0] = num & 0x00FF; // low byte
}

输出:

16
-16
11
245

【问题讨论】:

  • 什么是byte?是typedef 类型吗?如果是这样,请包括它的定义。

标签: c++ byte short


【解决方案1】:

来自ShortToByte

bytes[1] = num & 0xFF00; // high byte

您必须将其向右移动 8 位,以使结果适合一个字节。否则你只会从低部分得到零。

【讨论】:

    【解决方案2】:

    我会说使用联合会更容易:

    union ShortByteUnion {
        signed  short asShort;
        unsigned char asBytes[2];
    };
    

    它会为您处理转换。

    【讨论】:

      【解决方案3】:

      只需将 short 转换为字节数组。

      signed short test = 1234;
      byte* b;
      
      b = (byte*) &test;
      
      b[0];//one byte
      b[1];//another byte
      

      在不止一种类型的机器上执行此操作很危险,因为字节序可能会有所不同。

      我不喜欢单行字,但他们来了:

      ((byte*)&test)[0];
      ((byte*)&test)[1];
      

      【讨论】:

        猜你喜欢
        • 2011-09-12
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        • 1970-01-01
        • 2012-01-16
        • 2017-12-05
        相关资源
        最近更新 更多