Weird bit shift behavior
I am porting some ANSI C ++ code to C # ... and it is killing me right now.
Both tests have value = 6844268
.
Test code:
value >> 12
value & 0x00000FFF
C ++ returns 18273 and 29497, whereas C # returns 1670 and 3948. I've tried every possible combination of types in C # (int, uint, long, ulong, Int64 ...) but not go :(
The original value in C ++ is unsigned int. Does anyone have any idea?
EDIT: Arg, I messed up my debugging. Looked at array [value] instead of value. My bad one.
source to share
Check your C ++ definitions for overridden operator code >>
?
C # calculates the correct values, are you absolutely 100% sure that your values are what you say?
Just to go through the motions:
6844268 = 11010000110111101101100
>> 12 = 11010000110.111101101100
result = 11010000110
result = 2 + 4 + 128 + 512 + 1024 = 1670
18273 = 100011101100001
6844268 >> 12 = 11010000110
^^^^ ^^^ <-- mismatches
they don't line up, there must be some details that you don't see in your code.
source to share
I don't know what C ++ is, but on my calculator the C # values are correct; this is possibly a sign extension issue (the C ++ value is negative and the shift is dragging the top 1 bit with it?)
Also, given that 0xFFF is 4095, there is no way and the operation could return a value greater than that.
source to share
Seems right to me ...
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;
};
source to share
There is no overridden -> operator. This is the relevant C ++ code snippet:
[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 added for wolf debugging.
cout output:
6844268 | cout << value
2 | sizeof(unsigned short)
18273 | slt... Ohhhh sneaky. I mis-pasted that, nevermind - it an slt issue [Output the same now]
29497
source to share