skip to Main Content

I’m researching the rhythmic elements of prime number sequences in binary. I have multiple sets of files containing vertical lists, and I want to apply bitwise logic operators between any two of them line-by-line.

i.e.

$cat binary-superprimes.txt
11
101
1011
10001
11111
101001
111011
1000011
1010011
1101101
$cat binary-perniciousprimes.txt 
11
101
111
1011
1101
10001
10011
11111
100101
101001

I’m looking for commands, a script, or an application (I’d prefer commands/a script but its not deal-breaking) that will let me and/or/xor/etc. these outputs in order line-by-line, in much the same style/similar to the output of diff or comm.

Using CentOS 7/Ubuntu 18.04/MacOS 10.15.

edit
Expected output (binary expansion of XORing each entry above in decimal):

0
0
1100
11010
10010
111000
101000
1011100
1110110
1000100

As for what I’ve tried, as I said I’ve played around with for loops, but I don’t know how (or if its possible) two iterate two lists for comparison in this context (i.e. two “for i in”‘s with a single “done” – using $i and $x as inputs for a basic “echo (($x^$i))”

I’ve also tried a program called “bitwise” but its output is too verbose and it cannot seem to read files, only values.

2

Answers


  1. You can use bc for this purpose. First you create file

    xor.bc

    define xor(x,y) {
     auto n,z,t,a,b,c,os,qx,qy;
     os=scale;scale=0
     n=0;x/=1;y/=1
     if(x<0){x=-1-x;n=!n}
     if(y<0){y=-1-y;n=!n}
     z=0;t=1;while(x||y){
      qx=x/4;qy=y/4;
      c=(a=x-4*qx)+(b=y-4*qy) 
      if(!c%2)c=a+4-b         
      z+=t*(c%4)
      t*=4;x=qx;y=qy
     }
     if(n)z=-1-z
     scale=os;return (z)
    }
    

    Then you create loop to get the numbers one by one. And you can exec XOR by this:

    paste binary-superprimes.txt binary-perniciousprimes.txt |while read var1 var2;
    do
        echo "ibase=2;obase=2;xor($var1;$var)|bc -l xor.bc
    done
    
    Login or Signup to reply.
  2. Assuming your bash version is >= 4.0 and supports mapfile,
    would you try the following:

    mapfile -t x < "binary-superprimes.txt"
    mapfile -t y < "binary-perniciousprimes.txt"
    
    for (( i=0; i<${#x[@]}; i++ )); do
        echo "obase=2;" $(( 2#${x[i]} ^ 2#${y[i]} )) | bc
    done
    

    Output:

    0
    0
    1100
    11010
    10010
    111000
    101000
    1011100
    1110110
    1000100
    

    In case your bash does not support mapfile command, please try the alternative:

    while read -r line; do
        x+=($line)
    done < "binary-superprimes.txt"
    
    while read -r line; do
        y+=($line)
    done < "binary-perniciousprimes.txt"
    
    for (( i=0; i<${#x[@]}; i++ )); do
        echo "obase=2;" $(( 2#${x[i]} ^ 2#${y[i]} )) | bc
    done
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search