Skip to main content
6 of 6
syntax highlighting

Bash 440 430 412 405 403

A=0
[ test != "$1" ]&&for((D=0;D<${#1};D++)){
A=$((A+`bc<<<$(printf "obase=2;%d" "'${1:$D:1}")|tr -d "0
"|wc -m`))
}
echo $A

Pretty straightforward. Loops characters in the input converting first to ascii (with printf %d and the leading ' on the number then to binary (with bc), strips out the zeros and counts the number of characters.

Not a great answer but hadn't seen a bash attempt yet.

Modified since my first answer allowed the input string to be given simply on the command line (i.e. it became multiple input params if multipe words) but after reading some other answers I think I can assume it is quoted, so the whole string comes as $1

Adam
  • 151
  • 4