⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 use rotations to encode a message.cpp

📁 一个很有用的c++程序 对初学者很有用 功能强大 解释清楚DocumentsUserotations
💻 CPP
字号:
// Use rotations to encode a message. 
 
#include <iostream> 
#include <cstring> 
using namespace std; 
 
unsigned char rrotate(unsigned char val, int n); 
unsigned char lrotate(unsigned char val, int n); 
void show_binary(unsigned int u); 
 
int main() 
{ 
  char msg[] = "This is a test."; 
  char *key = "xanadu"; 
  int klen = strlen(key); 
  int rotnum; 
 
  cout << "Original message: " << msg << "\n"; 
 
  // Encode the message by left-rotating. 
  for(int i = 0 ; i < strlen(msg); i++) { 
    /* Left-rotate each letter by a value 
       derived from the key string. */ 
    rotnum = key[i%klen] % 8; 
    msg[i] = lrotate(msg[i], rotnum); 
  } 
 
  cout << "Encoded message: " << msg << "\n"; 
 
  // Decode the message by right-rotating. 
  for(int i = 0 ; i < strlen(msg); i++) { 
    /* Right-rotate each letter by a value 
       derived from the key string. */ 
    rotnum = key[i%klen] % 8; 
 
    msg[i] = rrotate(msg[i], rotnum); 
  } 
 
  cout << "Decoded message: " << msg << "\n"; 
 
  return 0; 
} 
 
// Left-rotate a byte n places. 
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. 
} 
 
// Right-rotate a byte n places. 
unsigned char rrotate(unsigned char val, int n) 
{ 
  unsigned int t; 
 
  t = val; 
 
  // First, move the value 8 bits higher. 
  t = t << 8; 
 
  for(int i=0; i < n; i++) { 
    t = t >> 1; 
 
    /* If a bit shifts out, it will be in bit 7 
       of the integer t. If this is the case, 
       put that bit on the left side. */ 
    if(t & 128)  
      t = t | 32768; // put a 1 on left end 
  } 
 
  /* Finally, move the result back to the 
     lower 8 bits of t. */ 
  t = t >> 8; 
 
  return t; 
} 
 
// 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"; 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -