Advertisement
TrickmanOff

vvvv

Sep 7th, 2020
1,219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. ifstream in("input.txt");
  7. ofstream out("output.txt");
  8.  
  9. int encode_bytes_num(int char_code) {
  10.     if (char_code >= (1 << 16)) {
  11.         return 4;
  12.     } else if (char_code >= (1 << 11)) {
  13.         return 3;
  14.     } else if (char_code >= (1 << 7)) {
  15.         return 2;
  16.     } else {
  17.         return 1;
  18.     }
  19. }
  20.  
  21. /*
  22.  1000 0000 - 80
  23.  1100 0000 - C0
  24.  1110 0000 - E0
  25.  1111 0000 - F0
  26.  
  27.  7  - 0xxxxxxx
  28.  11 - 110xxxxx 10xxxxxx
  29.  16 - 1110xxxx 10xxxxxx 10xxxxxx
  30.  21 - 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  31.  */
  32.  
  33. // encodes char with binary 'char_code' to utf-8 character
  34. string encode(int char_code) {
  35.     int byte_cnt = encode_bytes_num(char_code);
  36.    
  37.     int first_byte[] = {0, 0, 0xC0, 0xE0, 0xF0};
  38.    
  39.     int code[4];
  40.    
  41.     code[0] = first_byte[byte_cnt];
  42.     for (int byte = byte_cnt - 1; byte >= 1; --byte) {
  43.         code[byte] = 0x80 + char_code % (1 << 6);
  44.         char_code >>= 6;
  45.     }
  46.    
  47.     code[0] += char_code;
  48.     return string(code, code + byte_cnt);
  49. }
  50.  
  51. int main() {
  52.     int char_code;
  53.     in >> char_code;
  54.     while (in >> char_code) {
  55.         out << encode(char_code);
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement