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

StackOverflow https://stackoverflow.com/questions/23669823

  •  23-07-2023
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução 2

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

Outras dicas

In C++, i << 1 is equivalent to i * 2, if i is an unsigned integer.

This is nothing to do with "converting 16bit integer to 8bit". One way to do that is to mask off all the bits except the lower 8: (number & 0xFF) or equivalently (number % 256).

If you multiply by 2 and then do this conversion, you will get 0 after 254. But that is still not what you want. Your target output has 1 added to the second half.

So, to get that you could use:

for (int i = 0; i < 256; i++)
    number = (i * 2) % 256 + (i >= 128);

It looks like Matlab is doing circular 8-bit shift, when abcdefgh << 1 becomes bcdefgha. C++ has no such thing, but you may simulate it by

number = ((i << 1) & 0xff) | (i>> 7);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top