Linda, here are some utilities for working with signed binary numbers.
Thanks to Don Guinn for a neat idea. Kip
NB. 32-"bit" signed binary numbers -- produced by verb sb
NB. negative is - absolute value
guinn =: * * (32#2) #: | NB. Don Guinn, used in sb
sb =: guinn`([: smoutput 'overflow!'"_)@.(4294967295 < |)"0
] 'a b' =: sb _5 3
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 _1 0 _1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
sb 2^32
overflow!
dv =: (2 p.~ |.)"1 NB. decimal value
dv a ,: b
_5 3
sh0 =: [: (''"_`0:@.(0=#) , ]) (}.~ 1 i.~ |) NB. used in sh
sh =: [: |."1 |.@sh0"1 NB. shorten by trimming leading zeros
(sh a) ; (sh b)
+-------+---+
|_1 0 _1|1 1|
+-------+---+
sh a ,: b
_1 0 _1
0 1 1
db =: [: sh sb NB. display short form of binary
db _5 3
_1 0 _1
0 1 1
add =: ([: sb +&dv)"1
mul =: ([: sb *&dv)"1
sh c =: a (add ,: mul) b
0 0 _1 0
_1 _1 _1 _1
dv c
_2 _15
dv a ,: b
_5 3
sub =: ([: sb -&dv)"1
sh d =: a sub b
_1 0 0 0
dv d
_8
neg =: -@]"1
sh a ,: b
_1 0 _1
0 1 1
sh neg a ,: b
1 0 1
0 _1 _1
I needed conjunctions!
On 12/27/2011 2:34 AM, Linda Alvord wrote:
> Here are my latest thoughts on negative binary numbers.
>
> a=:1 0 0 1 1 0 1
> #.a
> 77
> b=:-a
> b
> _1 0 0 _1 _1 0 _1
> #.b
> _77
>
> The challenge is to get from _77 to _1 0 0 _1 _1 0 _1 which should be
> the result that #: provides. But that is not what happens:
>
> #:#.b
> 0 1 1 0 0 1 1
> #.#:#.b
> 51
>
> So here is a script which does that. It has lots of possibilities for
> simplification but it does give an idea of a possible approach. If someone
> can write the parts in loops or recursive style it would be interesting to
> compare results. I'm not a J programmer, but rather a J user who would like
> #: to work.
> Have fun, share your ideas.
>
>
> ]n=:15
> NB.Number of places like 4 for a 4 digit number
> d=: 13 :'-?y#2'
> d
> ]dd=:d n
> NB. d creates an n digit negative binary number
> w=: 13 :'2^|.i.y'
> w
> w n
> NB. w is a weighting list for each place value
> ]nd=:#.dd
> NB. nd converts a negative binary to a negative decimaldecimal number
> NB.nd=:_432532 insert a specific decimal to convert it
> ]p=:+/nd<-w 20
> ]b1=:-1=<.nd%-w n
> ]r1=:nd-#.b1
> ]b2=:-1=<.r1%-w n
> ]r2=:nd-#.b1+b2
> ]b3=:-1=<.r2%-w n
> ]r3=:nd-#.b1+b2+b3
> ]b4=:-1=<.r3%-w n
> ]r4=:nd-#.b1+b2+b3+b4
> ]b5=:-1=<.r4%-w n
> ]r5=:nd-#.b1+b2+b3+b4+b5
> ]b6=:-1=<.r5%-w n
> ]r6=:nd-#.b1+b2+b3+b4+b5+b6
> ]b7=:-1=<.r6%-w n
> ]r7=:nd-#.b1+b2+b3+b4+b5+b6+b7
> ]b8=:-1=<.r7%-w n
> ]r8=:nd-#.b1+b2+b3+b4+b5+b6+b7+b8
> ]b9=:-1=<.r8%-w n
> ]nb=:b1+b2+b3+b4+b5+b6+b7+b8+b9
> #.nb
> NB. nb has created the correct negative binary number
> ]dd
> #.dd
> ]p
> NB.nb id the binary created from a negative decimal number
> #:nd
> #.#:nd
> NB. results with problems
>
> Linda
>
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm