【发布时间】:2018-07-11 03:10:59
【问题描述】:
我正在尝试将一个很长的字符串转换为 ASCII 十六进制。
我该怎么做呢?
我已经写了这个很长的 switch 语句,但我知道有一种更简单的方法可以做到这一点。我在 switch 语句中遇到了所有奇数符号(如括号、#、$、\ 等)的问题。我可以让其中一些使用反斜杠,但其他一些则失败。
proc Text_to_ASCII {string} {
set Ascii_Word ""
set stringLength [string length $string]
for {set i 0} {$i < $stringLength} {incr i} {
set Letter [string index $string $i]
switch -glob $Letter {
" " {set hex_ascii 20}
0 {set hex_ascii 30}
1 {set hex_ascii 31}
2 {set hex_ascii 32}
3 {set hex_ascii 33}
4 {set hex_ascii 34}
5 {set hex_ascii 35}
6 {set hex_ascii 36}
7 {set hex_ascii 37}
8 {set hex_ascii 38}
9 {set hex_ascii 39}
A {set hex_ascii 41}
B {set hex_ascii 42}
C {set hex_ascii 43}
D {set hex_ascii 44}
E {set hex_ascii 45}
F {set hex_ascii 46}
G {set hex_ascii 47}
H {set hex_ascii 48}
I {set hex_ascii 49}
J {set hex_ascii 4A}
K {set hex_ascii 4B}
L {set hex_ascii 4C}
M {set hex_ascii 4D}
N {set hex_ascii 4E}
O {set hex_ascii 4F}
P {set hex_ascii 50}
Q {set hex_ascii 51}
R {set hex_ascii 52}
S {set hex_ascii 53}
T {set hex_ascii 54}
U {set hex_ascii 55}
V {set hex_ascii 56}
W {set hex_ascii 57}
X {set hex_ascii 58}
Y {set hex_ascii 59}
Z {set hex_ascii 5A}
a {set hex_ascii 61}
b {set hex_ascii 62}
c {set hex_ascii 63}
d {set hex_ascii 64}
e {set hex_ascii 65}
g {set hex_ascii 67}
h {set hex_ascii 68}
i {set hex_ascii 69}
j {set hex_ascii 6A}
k {set hex_ascii 6B}
l {set hex_ascii 6C}
m {set hex_ascii 6D}
n {set hex_ascii 6E}
o {set hex_ascii 6F}
p {set hex_ascii 70}
q {set hex_ascii 71}
r {set hex_ascii 72}
s {set hex_ascii 73}
t {set hex_ascii 74}
u {set hex_ascii 75}
v {set hex_ascii 76}
w {set hex_ascii 77}
x {set hex_ascii 78}
y {set hex_ascii 79}
z {set hex_ascii 7A}
default {set hex_ascii 3F}
}
append Ascii_Word $hex_ascii
}
return $Ascii_Word
}
所以我一直在尝试这段代码......
proc string2hex {s} {
binary scan $s H* hex
regsub -all (..) $hex {\\x\1}
}
set input_string "lol"
set ascii_string [string2hex $input_string]
返回 "\x6c\x6f\x6c" 这与我想要的“6c6f6c”非常接近 如何删除 \x?我正在考虑只做两次 trimleft 来摆脱每个字符的 \x ,也许一次只喂这个东西一个字符......
想法???
【问题讨论】:
-
您如何定义这种转换?你想要一个只有 7 位字符的字符串吗?不在 ASCII 集中的字符应该怎么办?您希望得到什么样的字符作为输入?
-
只有 7 位字符可以在键盘上键入。我需要将书面文字转换为 ASCII。我使用的软件只会接受 ASCII 输入。 “将我转换为 ASCII” 是一个完美的例子。我考虑过在for循环中手动扫描每个字母,然后使用带有char到ascii转换的switch语句,然后将它们拼接在一起,但我猜在tcl中有一种非常简单的方法可以做到这一点使用 [format] 调用,但我对 tcl 不是很了解,也无法弄清楚。
-
如果我输入“?到 ascii 的 proc 字符串中,我希望返回 3F 的值。我不知道您是否称其为 unicode 值或什么。
-
我想要达到的目的... UTF-8 是一种将所有 Unicode 字符转换为可变长度字节编码的方法;单个 Unicode 字符可以用一个、两个或三个字节表示。 UTF-8 标准的优势在于它和 Unicode 标准的设计使得与标准 ASCII 集(最多 ASCII 值 0x7F 的十六进制)对应的 Unicode 字符在 UTF-8 和 ASCII 编码中具有相同的字节值。换句话说,大写的“A”字符在 UTF-8 和 ASCII 编码中都由单字节值 0x41 表示。
-
我添加了一些建议。
标签: string char format tcl ascii