Left rotate functions for byte values : shift « Data Types « C++ Tutorial






/*
Quote from: C++: A Beginner's Guide, Second Edition 

# Publisher: McGraw-Hill Osborne Media; 2 edition (December 3, 2003)
# Language: English
# ISBN-10: 0072232153
# ISBN-13: 978-0072232158
*/


#include <iostream> 
using namespace std; 
 
unsigned char lrotate(unsigned char val, int n); 

void show_binary(unsigned int u); 
 
int main() 
{ 
  char ch = 'A'; 
 
  cout << "Original value in binary:\n"; 
  show_binary(ch); 
 
  cout << "Rotating left 8 times:\n"; 
  for(int i=0; i < 8; i++) { 
    ch = lrotate(ch, 1); 
    show_binary(ch); 
  } 
  return 0; 
} 
 
unsigned char lrotate(unsigned char val, int n) 
{ 
  unsigned int t; 
 
  t = val; 
 
  for(int i=0; i < n; i++) { 
    t = t << 1; 
 
    /* If a bit shifts out, it will be in bit 8 
       of the integer t. If this is the case, 
       put that bit on the right side. */ 
    if(t & 256) 
      t = t | 1; // put a 1 on the right end 
  } 
 
  return t; // return the lower 8 bits. 
} 
 
// Display the bits within a byte. 
void show_binary(unsigned int u) 
{ 
  int t; 
 
  for(t=128; t>0; t = t/2) 
    if(u & t) cout << "1 "; 
    else cout << "0 "; 
 
  cout << "\n"; 
}
Original value in binary:
0 1 0 0 0 0 0 1
Rotating left 8 times:
1 0 0 0 0 0 1 0
0 0 0 0 0 1 0 1
0 0 0 0 1 0 1 0
0 0 0 1 0 1 0 0
0 0 1 0 1 0 0 0
0 1 0 1 0 0 0 0
1 0 1 0 0 0 0 0
0 1 0 0 0 0 0 1








2.14.shift
2.14.1.Shift left
2.14.2.Shift right
2.14.3.Left rotate functions for byte values
2.14.4.Right rotate functions for byte values
2.14.5.Demonstrate bitwise left shift
2.14.6.Demonstrate bitwise right shift