1

What might be the most concise way in bash to convert a number into a bitfield character string like 1101?

In effect I am trying to do the opposite of

echo $[2#1101]

Why: I need to send a parameter to a program that takes bitfields in the form of a full string like "0011010110" but often only need to enable one or few bits as in:

SUPPRESSbits=$[1<<16] runscript.sh  # OR
SUPPRESSbits=$[1<<3 + 1<<9] runscript.sh  # much more readable when I know what bits 3 and 9 toggle in the program

Then runscript.sh then sees in its env a SUPPRESSbits=65536 rather than SUPPRESSbits="1000000000000000" and ends in parse error.

2 Answers 2

6

The easy way:

$ dc <<<2o123p
1111011

$ bc <<<'obase=2; 123'
1111011
Sign up to request clarification or add additional context in comments.

1 Comment

Great, it can hardly get more concise than with dc there. So bash doesn't seem to have number-to-string built in
1

I doubt about bash but you always can use perl:

a=123; b=$(perl -e 'printf "%b", "'$a'"'); echo $b
1111011

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.