@@ -28,33 +28,46 @@ INCLUDE_SEEN_PSST="${INCLUDE_SEEN_PSST-} _conv.inc.sh_"
28
28
# charCode: Character code of desired character.
29
29
#
30
30
# RETURNS
31
- # 0: Character code was valid .
32
- # 1 : Character code was no integer number.
33
- # 2 : Character code was out of valid range (0-255).
34
- # 3: Character code is newline (`\n``), which cannot be captured .
31
+ # 0: Success .
32
+ # 2 : Character code was no integer number.
33
+ # 3 : Character code was out of valid range (0-255).
34
+ # 4: One or more trailing newline characters (\n) have been dropped .
35
35
#
36
36
# OUTPUT
37
37
# stdout: The character whose code is `charCode`.
38
38
#
39
+ # NOTE
40
+ # To prevent that trailing newlines are getting dropped, just append an extra
41
+ # charcode and later on strip that char again as shown in the sample code.
42
+ #
39
43
# SAMPLE
40
44
# digit9=$( chr_psst 57 )
41
45
#
46
+ # # Prevent newlines from getting dropped
47
+ # newline=$( chr_psst 10 95 )
48
+ # newline=${newline%_} # strip "_" at end as 95 == "_"
49
+ #
42
50
conv_chr_psst ()
43
51
(
44
52
func=" chr_psst"
45
53
assert_minargc_psst " $func " 1 $#
46
54
assert_hasarg_psst " $func " " charCode" " $1 "
47
55
48
- while [ -n " ${1-} " ]
56
+ for char in " $@ "
49
57
do
50
- charCode=$1
51
- test_is_int_psst " $charCode " || return 1
52
- { [ " $charCode " -lt 0 ] || [ " $charCode " -gt 255 ]; } && return 2
53
- [ " $charCode " != " 10" ] || return 3
54
-
55
- printf " %b" " $( printf ' \%o' " $charCode " ) "
56
- shift
58
+ test_is_int_psst " $char " || return 2;
59
+ { [ " $char " -lt 0 ] || [ " $char " -gt 255 ]; } && return 3
57
60
done
61
+
62
+ if [ $# -eq 1 ]
63
+ then
64
+ printf " %b" " $( printf ' \\0%o' " $char " ) "
65
+ else
66
+ printf " %s" " $* " | xargs printf ' \\\\0%o' | xargs printf " %b"
67
+ fi
68
+
69
+ [ " $char " -eq 10 ] && return 4
70
+ return 0
58
71
)
59
72
60
73
@@ -87,16 +100,7 @@ conv_ord_psst()
87
100
chars=$1
88
101
[ ${# chars} -eq 1 ] && { LC_CTYPE=C printf " %d" " '$chars " ; return 0; }
89
102
90
- printf " %s" " $chars " | (
91
- sep=
92
- while read -r _unused_ octalValue << EOF
93
- $( dd bs=1 count=1 2> /dev/null | od -b )
94
- EOF
95
- do
96
- [ -n " $octalValue " ] || return 0
97
- LC_CTYPE=C printf " %s%d" " $sep " " 0$octalValue "
98
- sep=" "
99
- done
100
- )
101
-
103
+ printf " %s" " $chars " \
104
+ | od -t u1 \
105
+ | awk ' {for(i=2;i<=NF;i++){printf "%s%s",sep,$i;sep=" "}}'
102
106
)
0 commit comments