0

How do you define a binary number in a shell script? I tried it with the 0bprefix, but that doesn't work for some arbitrary reason. Octal and hex works fine.

Here's the code I'm trying to run:

#!/bin/sh
test=0b0010;
value=0b0001;

if [ $((value & test)) > 0 ]; then
        echo "true";
else
        echo "false";
fi

Also, I'm new to shell scripts and is there any better or "proper" way to check if a bit is set?

4
  • Can you just use hexadecimal? It's easy to convert binary to hexadecimal: four digits binary = one digit hex Commented Dec 26, 2019 at 12:48
  • Yes I can, but I'm still curious if there's a way to use binary and it's easier in binary Commented Dec 26, 2019 at 12:49
  • Hi Sheldon Does this help ? stackoverflow.com/a/47920047/1123335 Commented Dec 26, 2019 at 14:00
  • @pnorton No, not really. I actually just want to know if there's a way to say, that this should be treated as a binary number, but it seems there's no way so I'll just use hex, but thank you anyways Commented Dec 26, 2019 at 14:51

1 Answer 1

5

I don't think there is a POSIX shell syntax to define numbers in non-decimal (unless you use an external program such as bc to do the conversion for you):

b2d()( echo "ibase=2; $1" | bc )

test=$(b2d 0010)
value=$(b2d 0001)

However, if you are using bash, you can use let or ((...)):

let "test = 2#0010 "
let "value=2#0001"
((test = 2#0010))
((value=2#0001 ))
test=$(( 2#0010))
value=$((2#0001))

After this, you can check as you did in your question, or simplify to:

if (( value & test )); then
    echo true
else
    echo false
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, bc is key. Works just as well from binary-to-decimal and decimal-to-binary with obase and ibase (in that order)

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.