signiert kurz, um byte in c++
Ich versuche zum konvertieren einer Hexadezimalzahl in eine short (2 Bytes) mit C++
alles ist OK bis auf eine Sache... unterzeichnet Konvertierung von short nach Byte (letzter test)
fand ich diese Frage und konnte nicht wirklich davon profitieren können: portable signed/unsigned-byte-cast,C++
hier meine tests:
//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;
Funktionen verwendet:
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
}
Ausgänge:
16
-16
11
245
- Warum nicht eine Gewerkschaft?
- Was ist ein
byte
? Ist es eintypedef
geben? Wenn ja, bitte fügen Sie Ihre definition.
Du musst angemeldet sein, um einen Kommentar abzugeben.
Vom
ShortToByte
:Müssen Sie shift nach rechts 8 bits für das Ergebnis passen in ein byte. Ansonsten wird Ihnen nur die Nullen von den niedrigen Teil.
Ich würde sagen, dies wäre viel einfacher, mit einem union:
Er kümmert sich um die Konvertierung für Sie.
Nur Besetzung, die kurz-bis byte-array.
Es ist gefährlich, was zu tun ist auf mehr als einem Typen der Maschine, weil endian Typ variieren.
Ich mag keine Einzeiler, aber hier gehen Sie: