Skip to content

Instantly share code, notes, and snippets.

@ess
Created October 1, 2010 23:23
Show Gist options
  • Save ess/607056 to your computer and use it in GitHub Desktop.
Save ess/607056 to your computer and use it in GitHub Desktop.
bn_create() {
local s="${1}"
local sign='+'
local lastdigit='0'
local len=${#s}
(( len-- ))
declare -a digits
local c=''
local count=0
local index=''
for ((c=len; c>0; c-- ))
do
digits[${#digits[@]}]=${s:${c}:1}
done
if [ "${s:0:1}" == '-' ] || [ "${s:0:1}" == '+' ]
then
sign="${s:0:1}"
else
digits[${#digits[@]}]=${s:0:1}
fi
bn_sanitize "${sign}|${digits[*]}"
}
bn_sanitize() {
local n="${1}"
local nSign="$( bn_sign "${n}" )"
local nDigits=( $( bn_digits "${n}" ) )
while [ ${#nDigits[@]} -gt 1 ] && [ ${nDigits[$(( ${#nDigits[*]} - 1))]} -eq 0 ]
do
unset nDigits[$(( ${#nDigits[*]} - 1))]
done
[ ${#nDigits[*]} -eq 1 ] &&
[ "${nDigits[0]}" -eq 0 ] &&
nSign='+'
echo -n "${nSign}|${nDigits[*]}"
}
#!/bin/bash -
source ../bignum.sh
testBignumSanitize() {
local a='+|4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0'
assertEquals "Sanitize failed." "$( bn_sanitize "${a}" )" '+|4'
}
testBignumCreation() {
local a="$( bn_create 12345 )"
local nega="$( bn_create -12345 )"
local z="$( bn_create 0 )"
local negz="$( bn_create -0 )"
assertEquals "a != '+|5 4 3 2 1'" '+|5 4 3 2 1' "${a}"
assertEquals "nega != '-|5 4 3 2 1'" '-|5 4 3 2 1' "${nega}"
assertEquals "z != '+|0'" '+|0' "${z}"
assertEquals "negz != '+|0'; 0 is always positive" '+|0' "${negz}"
}
source ./shunit2/shunit2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment