Hello All,
i have two 16 bit binaries that in two different variables, i want to perform a bitwise AND between the two and store the result in a different variable.
can anyone throw some light on doing this in a bourne shell...
eg var1= 1110101010101011
bit wise and with var2= 1111111111111110
----------------------
result = 1110101010101010
You cannot use bourne shell alone to do that. bash has bitwise operators as builtins.
You will have to resort to another interpreted language like perl, or a compiled language like C, if you cannot switch to bash at all.
c example:
// and.c usage: ./and 34 0 not binary numbers
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if(argc==3)
{
int a=atoi(argv[1]);
int b=atoi(argv[2]);
printf("%d\n", a & b);
return 0;
}
return 1;
}
can we compare the value in positions of the variables. For example break the bits and store in individual variables, and do the same with the second variable which is storing the other 16 bits.
ex 1010101010101010
break the value in to 16 variables so that
from right to left
var 0 = 0, var 1 = 1 var 2= 0 etc....till var 15
then
do the same with the second 16 bit binary
xvar 0 = 1 xvar 1 = 1 xvar 2 = 1
compare value
if var 0 = 0 and xvar 0 = 1 then result = 0..... store this in variable yvar 0
if var 1= 0 and xvar 1 = 1 then result = 0......store this in variable yvar 1
if var 2= 1 and xvar 2 = 0 then result = 0 ... store this in variable yvar 2
var [n] xvar[n] yvar[n]
so on till var 15
can anyone throw some light on doing this way.....
You can do something like this to split the value into bits:
typeset -i value=2#1110101010101011
typeset -i bit
typeset -i i=0
while (( value ))
do
bit[i++]=$(( value & 1 ))
(( value >>= 1 ))
done
for i in ${!bit[@]}
do
printf "bit %2d = %d\n" $i ${bit}
done
If you run this script you get
bit 0 = 1
bit 1 = 1
bit 2 = 0
bit 3 = 1
bit 4 = 0
bit 5 = 1
bit 6 = 0
bit 7 = 1
bit 8 = 0
bit 9 = 1
bit 10 = 0
bit 11 = 1
bit 12 = 0
bit 13 = 1
bit 14 = 1
bit 15 = 1
He never said otherwise, even though bash was suggested over and over. People can be surprisingly reluctant to disclose their shell. It can take 2-3 tries to get a better answer than "bourne".