Search code examples
c++opencv16-bit8-bit

How to convert 16 bit integer to 8 bit without loosing the data values of the 16 bit integer when the range of 16 bit integer is 0-255


int samples = 8;  

for (unsigned int i = 0; i < (pow(double(2),samples)-1); i++)
{
unsigned int number = i << 1;
}

I am doing the coding in C++ using Opencv library. I want to do bitshift through this and this should be in the range of 0-255 but it is crossing the 255 range and going till 508.

IN Matlab the bitshift operator keeps the range between 0-255. The pattern in matlab is 0,2,4...254,1,3,5...255. But in C++ its going 0,2,4,254,256,258...508. I want the same answer as the matlab. Please suggest me some idea to do that.


Solution

  • The sequence 0, 2, 4, 6, ..., 252, 254, 1, 3, 5, ..., 253, 255 (which appears to be what you're after based on the sequence you show) can be generated with:

    for (int i = 0; i != 257; i = (i == 254) ? 1 : i + 2)
        doSomethingWith (i);
    

    There's probably many other ways to generate that sequence as well, including what's probably a more readable dual-loop version, provided you can keep the body of the loops small:

    for (int i = 0; i < 256; i += 2) doSomethingWith (i); // 0, 2, 4, 6, ..., 254
    for (int i = 1; i < 256; i += 2) doSomethingWith (i); // 1, 3, 5, 7, ..., 255