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?

Sheldon
  • 376
  • 3
  • 14
  • Can you just use hexadecimal? It's easy to convert binary to hexadecimal: four digits binary = one digit hex – Rup Dec 26 '19 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 – Sheldon Dec 26 '19 at 12:49
  • Hi Sheldon Does this help ? https://stackoverflow.com/a/47920047/1123335 –  Dec 26 '19 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 – Sheldon Dec 26 '19 at 14:51

1 Answers1

3

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
jhnc
  • 11,310
  • 1
  • 9
  • 26