C/C++中的逻辑右移、算数右移、循环左移、循环右移

C/C++语言中逻辑右移和算数右移共享同一个运算符>>。编译器决定使用逻辑右移还是算数右移,根据的是运算数的类型。如果运算数类型是unsigned则采用逻辑右移,而signed则采用算数右移。对于signed类型的数据,如果需要使用算数右移,或者unsigned类型的数据需要使用逻辑右移,都需要进行类型转换。

  • 示例代码:
#include  

int main()
{
  int a = 0xFFFFFFFF;
  std::cout << std::hex << ((unsigned)a >> 1) << std::endl; // 逻辑右移
  std::cout << std::hex << (a >> 1) << std::endl; // 算数右移

  unsigned b = 0xFFFFFFFF;
  std::cout << std::hex << (b >> 1) << std::endl;
  std::cout << std::hex << ((int)b >> 1) << std::endl;

  return 0;
}

hui@hui-Lenovo-V1000:~/test$ g++ test.cpp

hui@hui-Lenovo-V1000:~/test$ ./a.out
7fffffff
ffffffff
7fffffff
ffffffff


C/C++中没有循环左移和循环右移打操作符,需要自己实现

  • 示例代码:
#include 

/*循环左移*/
unsigned rol(unsigned val, int size)
{
  unsigned res = val << size;
  res |= val >> (32 - size);
  return res;
}

/*循环右移*/
unsigned ror(unsigned val, int size)
{
  unsigned res = val >> size;
  res |= val << (32 - size);
  return res;
}

int main()
{
  unsigned x = 0x80000000;
  std::cout << std::hex << "rol(" << x << ", " << 2 << ") = ";
  std::cout << std::hex << rol(x, 2) << std::endl;
  unsigned y = 0x80000001;
  std::cout << std::hex << "ror(" << y << ", " << 2 << ") = ";
  std::cout << std::hex << ror(y, 2) << std::endl;

  return 0; 
}

hui@hui-Lenovo-V1000:~/test$ ./a.out
rol(80000000, 2) = 2
ror(80000001, 2) = 60000000

你可能感兴趣的:(C/C++)