將 ascii 字元轉換為 ascii 十六進位表示

將 ascii 字元轉換為 ascii 十六進位表示

如何在 AWK 腳本中將 ASCII 字元轉換為 ASCII HEX?

我想要按字母範圍循環

例子

for(i="a"; i<"g"; i++)
 print i;

注意:我想循環十六進位表示的範圍並列印字元。

答案1

在我看來你真的不需要全部那些角色...

$ awk 'BEGIN { chartable="abcdefghij" ; for (i=index(chartable, "a"); i<index(chartable, "g"); i++) { print substr(chartable, i, 1) } }'
a
b
c
d
e
f

答案2

建立一個包含所有 ASCII 字元的表,並使用 awk 內建函數index()在表中尋找字元。然後使用sprintf()將傳回的十進制值轉換index()為十六進制。

BEGIN {
    for (i = 0; i < 128; i++) {
       table = sprintf("%s%c", table, i);
    }
}

function chartohex (char) {
    return sprintf("0x%x", index(table, char));
}

END { # examples
   print chartohex("a");
   print chartohex("A");
   print chartohex("!");
}

將此程式碼放入檔案「foo」中並運行awk -f foo < /dev/null,您將看到「a」、「A」和「!」的 ASCII 值以十六進位列印。

答案3

awk 沒有像 python 那樣的 ord()、chr() 函數。您必須先在 BEGIN 區塊中建立數組,其索引是 ascii 字符,值是十進制數。

awk 'BEGIN {
 for (i = 0; i <= 255; i++) {
    t = sprintf("%c", i)
    a[t] = i
}

for( i=a["a"]; i < a["g"]; i++)
    print sprintf("%c",i)
}'
a
b
c
d
e
f

相關內容