I want to implement the simplest example. There are two numbers in binary system 0011 and 0101 . I want to apply the operation "KILLED OR" to them. The result is displayed as a binary number. It should be 0111 , I get 73.
Why is that?

 #!/bin/bash AA=0011 BB=0101 CC=$(($AA | $BB)) echo "Result: " $CC 
  • firstly, the result is displayed in decimal, secondly, input numbers are perceived as octal since they start from zero. I would suggest using bc - Mike
  • How to fix so that everything was in the binary system ?. If not difficult, show how to do it. - Alexey Nakhimov September

2 answers 2

Bash binary numbers are specified as a 2#число . Bash cannot output the binary result, you can use bc :

 #!/bin/bash AA=2#0011 BB=2#0101 CC=$(($AA | $BB)) echo -n "Result: " printf "%04d" `echo "obase=2;$CC" | bc` 
  • Yes, everything is fine. There is only one “but” - how to ensure that leading zeros are not discarded? It displays "111", but should "0111" ... I need all the bits for the analysis ..... - Alexey Nakhimov
  • one
    @AlexeyNakhimov While a dirty hack came to mind through printf in the decimal system. Barakin will come, surely prettier and shorter. From myself, I note that it may be worth using something more suited for working with bits, for example perl - Mike
  • 2
    Yes, I would have done it in Python. I just don’t want to create entities beyond what is necessary ... It is necessary to implement monitoring of the workload of several GPUs, did all the other necessary scripts in Bash, only that remains. The easiest way is through a binary number, where each bit corresponds to its own GPU and its status - 1 (all is well) and 0 (all is bad). And then periodically impose on it the previous value .... And if two times in a row the same GPU is bad, then report it. - Alexey Nakhimov September
  • @AlexeyNakhimov If you need zeros, and you know how much and do not disdain the pearl, then perl -e "printf \"%08b\n\", $((2#0011 | 2#0100))" . - Ainar-G
  • @AlexeyNakhimov here and do it! The only thing is that python is also bad with bats (it’s necessary to fence one’s own class or use someone’s options that are not always flexible). - 0andriy

Bash does not know how to output in binary form, but you can somehow (without bc):

 BA=({0..1}{0..1}{0..1}{0..1}) AA=2#0011 BB=2#0101 CC=${BA[$((AA|BB))]} echo $CC