How to copy MSB to the rest of the byte?

In the interrupt routine (called every 5 μs) I need to check the MSB byte and copy it to the rest of the byte.

I need to do something like:

if(MSB == 1){byte = 0b11111111}
else{byte = 0b00000000}

I need it to work quickly, like on an interrupt routine, and there is some more code on it, so efficiency is called.

Therefore, I do not want to use the operands of if, switch, select and >>, since I have a cut that slows down the process. If I am wrong, then I will go "easy."

What I tried:

byte = byte & 0b100000000

It gives me 0b10000000or 0b00000000.

But I need to be the first 0b11111111.

I think I have no OR (plus other gates). I don’t know, my courage tells me that this should be easy, but this is not for me at the moment.

+4
3

EDIT. , . , B unsigned char. , &1. , , , ( , B - ).

 B = -((B >> 7)&1)

- . , .

+3

, , int8_t, byte :

byte = byte >> 7;

- ( ) .

, >> , . .

.. , , . , ., .

+3

MSB is actually a bit of the sign of a number. It is 1 for a negative number and 0 for a positive number. so the easiest way to do this is

if(byte < 0)
{
    byte = -1;
}
else
{
    byte = 0;
}

because -1 = 11111111 in binary format.

If this is the case for an unsigned integer, simply enter it in a signed value and then compare it as above.

0
source

All Articles