При написании функций можно использовать только следующее: - целочисленные константы; - целочисленные аргументы функций и автоматические (локальные)переменные; - операции ~ ! + - (тип) << >> & ^ | . Группы операций расположены в порядке убывания приоритета. 
 int MoveRight(int x, int n, int onebit); MoveRight - сдвигает х вправо на n разрядов с заполнением значением 

onebit (only 0 or 1) freed bits Examples: MoveRight (0x123,4,1) = 0xF012 MoveRight (0x123,4,0) = 0x12

Thank you very much

  • one
    @Anatoly, if you don’t understand the assignment, then it’s best to ask him who gave it to you - it’s unlikely the teacher would like you to guess what he needs from you. - DreamChild
  • one
    Shift n digits to the right by filling in the vacant digits 1 or 0. Example: Initial number: 0000 0001 0010 0011 (0x123) Shift right 4 digits filling 0: 0000 0000 001 0010 (0x12) Shift right 4 digits filling 1: 1111 0000 001 0010 (0xF012) - MDJHD
  • 2
    @Anatoly, do you have an int type of two bytes (short), as in the given example? Or actually 4-byte, as in most implementations, but the function operates with only two low bytes, and the higher ones are 0? Or an example of this only for brevity? The implementation of the function depends very much on this. Decide what you need to do. - paulgri
  • one
    Provide unsigned argument. Shift to the right - it will automatically fill with zeros. If it is necessary to fill with ones, then you make a mask with ones in n higher digits and after the shift you impose it on the result (through OR). And determine the bitness of the argument in sizeof. Respectively in bits sizeof(x) \* CHAR_BIT (from limits.h) will turn out. Just do not forget that the sign bit is the oldest. When you shift signed to the right, it is distributed. So, you can just play around with casting. That is, in fact, the whole "theory". (Deciphering unfamiliar words can google). - avp
  • one
    Here is Bit Twiddling Hacks a lot of different things about bittik. - avp

1 answer 1

 #include <stdio.h> #include <conio.h> #include <iostream> using namespace std; int MoveRight(int x, int n, int bit) { return (unsigned int)x >> n | bit << (sizeof(int)*8-1) >> (n - 1); } int main() { cout << hex << MoveRight(0x123, 1, 1) << " " << MoveRight(0x123, 4, 0); _getch(); } 
  • In my opinion, bit << (sizeof(int)*8-1) with bit ==1 gives an undefined behavior, since 1 * 2^(sizeof(int)*8-1) not representable as int . - dzhioev