Strano comportamento a bit-shift
-
03-07-2019 - |
Domanda
Sto eseguendo il porting del codice ANSI C ++ su C # ... e questo mi sta uccidendo in questo momento.
Entrambi i test hanno value = 6844268
.
Codice test:
value >> 12
value & 0x00000FFF
C ++ restituisce 18273 e 29497, mentre C # restituisce 1670 e 3948. Ho provato ogni possibile combinazione di tipi in C # (int, uint, long, ulong, Int64 ...), ma niente da fare: (
Il valore originale in C ++ non è firmato int. Qualcuno ha qualche idea?
EDIT: Argh, ho incasinato il mio debug. Stavo guardando array [valore] invece di valore. Mio male.
Soluzione
Controlla le tue definizioni C ++ per il codice operatore > >
ignorato, forse?
C # sta calcolando i valori giusti, sei assolutamente sicuro al 100% che i tuoi valori siano quelli che dici che sono?
Giusto per esaminare i movimenti:
6844268 = 11010000110111101101100
>> 12 = 11010000110.111101101100
result = 11010000110
result = 2 + 4 + 128 + 512 + 1024 = 1670
18273 = 100011101100001
6844268 >> 12 = 11010000110
^^^^ ^^^ <-- mismatches
non si allineano, ci devono essere alcuni dettagli che non vedi nel tuo codice lì.
Altri suggerimenti
Non so cosa stia facendo C ++, ma sulla mia calcolatrice i valori C # sono corretti; è forse questo un problema di estensione del segno (il valore C ++ è negativo e lo spostamento sta trascinando il primo bit con esso ??)
Inoltre, dato che 0xFFF è 4095, non è possibile che & amp; l'operazione può restituire un valore superiore a quello.
Mi sembra corretto ...
sock@thebrain:~$ g++ test.cc
sock@thebrain:~$ ./a.out
6844268 1670 1670
6844268 1670 1670
sock@thebrain:~$ cat test.cc
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int value = 6844268;
printf("%u %u %u\n", value, value >> 12, (value >> 12)&0xFFF);
cout << value << " ";
cout << (value>>12) << " ";
value = (value>>12)&0xFFF;
cout << value << endl;
return 0;
};
Nessun override > > operatore. Questo è lo snippet di codice C ++ pertinente:
[Function signature: const unsigned char *src, int len, char *dst]
unsigned short *sdst = (unsigned short*) dst;
unsigned short *slt = (unsigned short*) lookup_ext;
while (len >= 3) {
unsigned int value = *src++ << 16;
value |= *src++ << 8;
value |= *src++;
cout << value << endl;
*sdst++ = slt[value >> 12];
*sdst++ = slt[value & 0x00000FFF];
cout << sizeof(unsigned short) << endl << slt[value >> 12] << endl << slt[value & 0x00000FFF] << endl;
len -= 3;
}
Cout è stato aggiunto per il debug della recinzione del lupo.
output cout:
6844268 | cout << value
2 | sizeof(unsigned short)
18273 | slt... Ohhhh sneaky. I mis-pasted that, nevermind - it's an slt issue [Output's the same now]
29497