clean up implementation via proper mask and counting bits