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

การแปลงสตริงเป็น Binary String (a-m=0, n-z=1) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีแปลงสตริงตัวพิมพ์เล็กเป็น Binary String โดย a-m -> 0, n-z -> 1 ตัวอักษรอื่น (Space, Punctuation) คงเดิม

ตัวอย่าง

Input:  'Hello worlld how are you'
Output: '00001 111000 011 010 111'
// h(7)=0, e(4)=0, l(11)=0, l(11)=0, o(14)=1 -> 00001
// space -> space
// w(22)=1, o(14)=1, r(17)=1, l(11)=0, l(11)=0, d(3)=0 -> 111000

การนำไปใช้

const stringToBinary = (str = '') => {
  const s = str.toLowerCase();
  let res = '';
  
  for (let i = 0; i < s.length; i++) {
    // Special characters (ไม่ใช่ตัวอักษร)
    if (s[i].toLowerCase() === s[i].toUpperCase()) {
      res += s[i];
      continue;
    }
    // a-m (97-109) -> 0, n-z (110-122) -> 1
    res += s[i] > 'm' ? '1' : '0';
  }
  return res;
};

console.log(stringToBinary('Hello worlld how are you'));

ผลลัพธ์

00001 111000 011 010 111

วิธีการทันสมัย

const stringToBinaryModern = (str) => 
  [...str.toLowerCase()].map(c => 
    /[a-z]/.test(c) ? (c > 'm' ? '1' : '0') : c
  ).join('');

// Regex Version
const stringToBinaryRegex = (str) => 
  str.toLowerCase().replace(/[a-z]/g, c => c > 'm' ? '1' : '0');

การขยาย: Custom Mapping

const customBinaryMap = (str, mappingFn) => 
  [...str].map(c => mappingFn(c)).join('');

// ตัวอย่าง: Vowel=1, Consonant=0
const vowelBinary = (str) => 
  [...str.toLowerCase()].map(c => 
    /[aeiou]/.test(c) ? '1' : /[a-z]/.test(c) ? '0' : c
  ).join('');

การประยุกต์ใช้

  • Simple Obfuscation / Encoding
  • Feature Extraction สำหรับ ML (Character-level)
  • Cryptography Exercises
  • Data Compression Preprocessing

ข้อควรระวัง

  • Case Insensitive: แปลงเป็น Lowercase ก่อน
  • Non-ASCII: ไทย, อิโมจิ, Accented Chars -> คงเดิม
  • ไม่ใช่ Encryption จริง (ง่ายมากที่จะถอดรหัส)