Zweiercomplement
-
Hallo,
Nochmal komme ich mit etwas das mich Schon Kopfschmerzen bereitet hat.
ich habe eine Variable das entwerder aus 2 Bytes(erste bit von Byte1 = 1) oder 1 byte(erste bit von Byte1 = 0) bestehen kann.
und der zeichen(sign) muss auch in beachtet werden.2 Byte value:
Byte1---------------------------------Byte2
sign B13 B12 B11 B10 B9 B8 1| B7 B6 B5 B4 B3 B2 B1 B01 Byte value:
Byte1
sign B5 B4 B3 B2 B1 B0 0so versuche ich es :
char Payload[30],Payload_Buff ; int PayloadInt_Tab[20]; if((Payload[i]&(char)0x10)==(char)0x10 ){ // aus zwei Bytes Payload_Buff = Payload[i-11] >> 1; Payload_Buff = Payload_Buff << 8; PayloadInt_Tab[m] = (Payload_Buff | Payload[i-11+1]); PayloadInt_Tab[m] = -((0xffff&(PayloadInt_Tab[m]-1))-32768); i = i+2; m = m+1; } else {// aus ein Byte PayloadInt_Tab[m] = Payload[i-11] >> 1; PayloadInt_Tab[m] = -((0xff&(PayloadInt_Tab[m]-1))-128); i = i+1; m = m+1; }
Kann mir vielleicht jemand sagen was ich da falsche mache oder wie ich das besser machen könnte ?
Grüß
Ryoban
-
und was willst du erreichen? Sorry, aber so ist dir nicht zu helfen.
-
Ich habe auch so gar nichts verstanden. Was ich verstanden habe ist, du willst 2 Bytes zu einem Word zusammentun. Und ich hab das Wort Zweierkomplement verstanden. Wenn du das haben willst und mit der Bitfrickelei so unheimliche Probleme hast, wieso machst du es dann nicht ganz einfach?
#include <iostream> #include <bitset> using namespace std; int make_word(char c1, char c2) { bitset<8> byte_1(c1); bitset<8> byte_2(c2); bitset<16> merge; for(int i=0; i!=16; ++i) merge[i] = i<8 ? byte_2[i] : byte_1[i-8]; return merge.to_ulong(); } int complement_on_two(int i) { bitset<16> word(i); word.flip(); return (word.to_ulong() +1); } int main() { char c1 = 1; char c2 = 2; int word = make_word(c1,c2); int zk = complement_on_two(word); cout << endl << word << endl << zk; }
-
Hallo,
danke für den Antwort
ich aber so gemacht und gespannt es zu testen :
for (int j = 0; i < length; j++){ if((Payload[i]&(char)0x01)==(char)0x01){ // Two bytes Datagramm if ((Payload[i])&(char)0x80 == (char)0x80){ //negativ Payload[i]=(Payload[i])&(char)0x7f; Payload_Buff = Payload[i] >> 1; Payload_Buff = Payload_Buff << 8; PayloadInt_Tab[m] = (Payload_Buff | 0xFFFF&Payload[i+1]); PayloadInt_Tab[m] = ~ PayloadInt_Tab[m]; PayloadInt_Tab[m] = -(PayloadInt_Tab[m] + 1); } else if ((Payload[i])&(char)0x8000 == (char)0x0000){//positiv Payload[i]=(Payload[i])&(char)0x7f; Payload_Buff = Payload[i] >> 1; Payload_Buff = Payload_Buff << 8; PayloadInt_Tab[m] = (Payload_Buff | 0xFFFF&Payload[i+1]); } i = i+2; m = m+1; } else { //one byte Datagramm if ((Payload[i])&(char)0x80 == (char)0x80){ //negativ Payload[i]=(Payload[i])&(char)0x7f; PayloadInt_Tab[m] = Payload[i] >> 1; PayloadInt_Tab[m] = ~ PayloadInt_Tab[m]; PayloadInt_Tab[m] = -(PayloadInt_Tab[m] + 1); } else if ((Payload[i])&(char)0x80 == (char)0x00){//positiv PayloadInt_Tab[m] = Payload[i] >> 1; } i = i+1; m = m+1; } } int n=0, j=0;
Grüß