Binary Arithmetic

   1 BA:=module() 
   2     export B,`+`,`-`,`*`,`/`,`^`;
   3     local c;
   4     option package;
   5     description "A package for binary arithmetic.", 
   6         "Usage: B(an expression with numbers in binary system);", 
   7         "Copyright (c) 2005 Alec Mihailovs <alec@mihailovs.com>";
   8     `+`:=()->:-`+`(args); 
   9     `-`:=()->:-`-`(args); 
  10     `*`:=()->:-`*`(args); 
  11     `/`:=()->:-`/`(args); 
  12     `^`:=()->:-`^`(args);
  13     c:=overload([
  14         proc(a::{float,integer}) option overload; convert(a,binary) end,
  15         proc(a::fraction) option overload; applyop(c,{1,2},a) end,
  16         proc(a::Not(numeric)) option overload; subsindets(a,numeric,c) end]);
  17     B:=(a::uneval)->c(eval(subsindets(a,numeric,x->convert(x,decimal,2)))) 
  18 end:

Here are some examples,

> with(BA):
> Digits:=30:
> B((10101-10)*11001+100101);
$$\mo{1000000000}$$ > B(101/110+10011/1101001);
$$\mo{1000111\ \over 1000110\ }$$ > B(11^10);
$$\mo{1001}$$ > B(evalf(Pi+10));
$$\mo{101.001001000011111101101010100}$$ > B(combine(sin(10)*cos(10)));
$$\mo{\frac{1}{10} \sin (100)}$$ > B(110!);
$$\mo{1011010000}$$ > B(sqrt(10));
$$\mo{10^{\(\frac{1}{10}\)}}$$ > B(sqrt(10.));
$$\mo{1.01101010000010011110011001100}$$ > B(11.0011^1.101);
$$\mo{110.100101000000010001101000111}$$ It still has a glitch with scientific notation,

> B(0.1*10^10000);
$$\mo{0.1000000000000000\ 10^{16}}$$

I also wrote a similar package for Octal Arithmetic

Completely different Binary Arithmetic package (not related to this one in any way, and having a similar glitch with scientific notation) was written by Douglas Wilhelm Harder and is available from his Maplesque page.

-- AlecMihailovs 2008-07-08 01:48:08


CategoryMaple

Maple/BinaryArithmetic (last edited 2008-07-08 08:21:23 by AlecMihailovs)