iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔁

Creating Commands to Convert Between Characters and Code Points

に公開

The process of converting between characters and code points is a common theme in shell scripting. Since I frequently use these conversions in test cases, I created commands in Bash, Python, and Rust.

Bash Implementation


Prepare the ord and chr files and write the following code.

ord
input="$1"
echo -n "$input" \
  | grep -oP . \
  | while IFS= read -r char; do
      printf '%X ' "'$char"
    done
echo
chr
for cp in "$@"; do
  printf '%b' "\\U$(printf '%08X' 0x$cp)"
done
printf '\n'

ord uses grep, but if the UTF-8 locale is set, index access can be used.

$ export LC_CTYPE=en_US.UTF-8

$ str="あいうえお"
$ echo "${#str}"
5     # ← Counts as number of characters!

$ echo "${str:0:1}"
あ    # ← Correctly extracts one character

Add execute permissions.

chmod +x ord
chmod +x chr

Install ord and chr in a directory on your PATH.

Check if the basic functionality works.

> ord あ
3042 
> chr 3042
あ

It also supports multiple characters and code points.

> ord あいうえお
3042 3044 3046 3048 304A 
> chr 3042 3044 3046 3048 304A
あいうえお

Python Implementation

Considering portability, I'll show a Python implementation.

ord
#!/usr/bin/env python3

import sys

text = sys.argv[1] if len(sys.argv) > 1 else ""
for char in text:
    print(f"{ord(char):X}", end=" ")
print()
chr
#!/usr/bin/env python3
import sys

def cps_to_chars(codepoints):
    chars = []
    for cp in codepoints:
        cp = cp.upper().lstrip("U+")
        try:
            chars.append(chr(int(cp, 16)))
        except ValueError:
            print(f"Invalid code point: {cp}", file=sys.stderr)
            sys.exit(1)
    return ''.join(chars)

if __name__ == "__main__":
    if sys.stdin.isatty():
        cps = sys.argv[1:]
    else:
        cps = sys.stdin.read().strip().split()

    print(cps_to_chars(cps))

Rust Implementation

Let's create two command tools in a single project. Create a folder called charutil.

Cargo.toml
[package]
name = "charutil"
version = "0.1.0"
edition = "2021"

[dependencies]
src/bin/ord.rs
fn main() {
    let input = std::env::args().nth(1).unwrap_or_default();
    for c in input.chars() {
        print!("{} ", char_to_hex(c));
    }
    println!();
}

fn char_to_hex(c: char) -> String {
    format!("{:X}", c as u32)
}
src/bin/chr.rs
use std::env;
use std::io::{self, Read};

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    let input = if !args.is_empty() {
        args.join(" ")
    } else {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf).unwrap();
        buf
    };

    for hex in input.split_whitespace() {
        match u32::from_str_radix(hex.trim_start_matches("U+"), 16)
            .ok()
            .and_then(std::char::from_u32)
        {
            Some(c) => print!("{}", c),
            None => eprintln!("Invalid codepoint: {}", hex),
        }
    }
    println!();
}

Build it.

cargo build

You can also build them individually.

cargo build --bin ord
cargo build --bin chr

Test it.

> target/debug/ord あ漢🍣
3042 6F22 1F363 
> target/debug/chr 3042 6F22 1F363
あ漢🍣
> echo "3042 6F22 1F363" | target/debug/chr
あ漢🍣
GitHubで編集を提案

Discussion