This shell script is useful for C defines or character arrays where you want a little-endian representation of some value in octal or hex. For example:
$ tle 153 \231\000
or if you're initializing a word:
$ tle 70053 4 \245\021\001\000
I hardlink it to tlex and it will output in hex format:
$ tlex 153 \x99\x00 $ tlex 70053 4 \xa5\x11\x01\x00
#!/bin/sh
# don't exec tclsh from tclsh \
exec tclsh $0 ${1+"$@"}
proc to_little_endian {n {size 2}} {
set lsb 0;
for {set x $n; set s [expr {$size - 1}]} {$s >= 0} {incr s -1} {
set msb($s) [expr $x >> (8 * $s)]
set x [expr $x - ($msb($s) << (8 * $s))]
}
set out ""
for {set s 0} {$s < $size} {incr s} {
append out [format "\\%03o" $msb($s)]
}
set out
}
proc to_little_endian_hex {n {size 2}} {
set lsb 0;
array set msb {}
for {set x $n; set s [expr {$size - 1}]} {$s >= 0} {incr s -1} {
set msb($s) [expr $x >> (8 * $s)]
set x [expr $x - ($msb($s) << (8 * $s))]
}
set out ""
for {set s 0} {$s < $size} {incr s} {
append out [format "\\x%02x" $msb($s)]
}
set out
}
proc tle {n {size 2}} {to_little_endian $n $size}
proc tlex {n {size 2}} {to_little_endian_hex $n $size}
if {$argc} {
if {[string match *x $argv0]} {
set r [eval [concat tlex $argv]]
} else {
set r [eval [concat tle $argv]]
}
puts $r
} else {
puts "usage:"
puts " Convert a decimal number to oct or hex in little endian format"
puts " tle output an octal value in little endian"
puts " tle output a hex value in little endian"
puts " tle <n> \[<size>\] where n is a decimal number and size is number of bytes"
puts " or tle x <n> \[<size>\] where n is a decimal number and size is number of bytes"
}