Monday, February 4, 2013

bash function to output set bits in a decimal integer

Doing some redesign of our webserver and wrote a quick shell function to give me the bitwise properties of a given integer. enjoy if you have any use for it. ./Stevo
  1 #!/bin/bash
  2
  3 function bitwise {
  4    val=$1
  5    if [[ ${val} -le $((2**8)) ]]; then
  6       max=8
  7    elif [[ ${val} -le $((2**16)) ]]; then
  8       max=16
  9    elif [[ ${val} -le $((2**32)) ]]; then
 10       max=32
 11    elif [[ ${val} -le $((2**64)) ]]; then
 12       max=64
 13    fi
 14    printf "binary: %0${max}dn" $(echo "obase=2; ${val}" | bc -l)
 15    for i in $(seq 1 ${max}); do
 16    if test  $((${val} & $(((1<<${i} - 1))))) -gt 0; then
 17       echo "bit:${i} set"
 18    fi
 19    done
 20 }

output:

stevenh@lnx:~$ bitwise 500
binary: 0000000111110100
bit:3 set
bit:5 set
bit:6 set
bit:7 set
bit:8 set
bit:9 set

No comments:

Post a Comment