Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลง String เป็น Binary Sequence ใน C++

ภาพรวมปัญหา

แปลงสตริงตัวอักษรเป็น Binary Sequence (ASCII → Binary) แยกด้วย Space

ตัวอย่าง

Input: "tutorialspoint"
Output: 1110100 1110101 1110100 1101111 1110010 1101001 1100001 1101100 1110011 1110000 1101111 1101001 1101110 1110100

วิธีแก้ปัญหา

  1. แต่ละ Char → ASCII Value (int)
  2. แปลงเป็น Binary (หาร 2 ซ้ำ เก็บ Remainder)
  3. Reverse Binary String → พิมพ์

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void convert_binary(string s) {
    int n = s.length();
    for (int i = 0; i < n; i++) {
        int val = int(s[i]);
        string bin = "";
        while (val > 0) {
            (val % 2) ? bin.push_back('1') : bin.push_back('0');
            val /= 2;
        }
        reverse(bin.begin(), bin.end());
        cout << bin << " ";
    }
}

int main() {
    string s = "tutorialspoint";
    convert_binary(s);
    return 0;
}

ผลลัพธ์ (Output)

1110100 1110101 1110100 1101111 1110010 1101001 1100001 1101100 1110011 1110000 1101111 1101001 1101110 1110100