使用時必須要是變數必須是陣列
如:
A= c(1,0,1,0,0)
B= c(0,1,1,1,0)
加法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#加法 plusBin5<-function(a,b){ flag=0 #進位旗標 for(i in 5:1){ if(flag==0){ if(a[i]==0 & b[i]==0){ a[i]=0 } else if(a[i]==0 & b[i]==1){ a[i]=1 } else if(a[i]==1 & b[i]==0){ a[i]=1 } else if(a[i]==1 & b[i]==1){ a[i]=0 flag=1 next } } if(flag==1){ if(a[i]==0 & b[i]==0){ a[i]=1 flag=0 } else if(a[i]==0 & b[i]==1){ a[i]=0 flag=1 } else if(a[i]==1 & b[i]==0){ a[i]=0 flag=1 } else if(a[i]==1 & b[i]==1){ a[i]=1 flag=1 } } } a[1]=flag return(a) } |
減法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#減法 minusBin5<-function(bigone,smallone){ #轉十進制 a=16 #最高位元是16 b=0 for(i in 1:5){ if(bigone[i]==1){ b=b+a } a=a/2 } #轉十進制 a=16 c=0 for(i in 1:5){ if(smallone[i]==1){ c=c+a } a=a/2 } #轉回二進制 ans=number2binary((b-c),5) return(ans) } number2binary = function(number, noBits) { binary_vector = rev(as.numeric(intToBits(number))) if(missing(noBits)) { return(binary_vector) } else { binary_vector[-(1:(length(binary_vector) - noBits))] } } |