Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write this C expression in J?

Tags:

c

j

How do I write this C expression in J? (where x is input integer, and a is temporary variable)

((a= ~x & (~x >> 1)) ^= a ? 0 : (a ^ (a & (a - 1))) | (a ^ (a & (a - 1))) << 1);

.

Edit:

In a more readable form:

    int a = (~x) & ((~x) >> 1);
    if (a == 0) return 0;
    int b = a ^ (a & (a - 1));
    return b | (b << 1);
like image 939
Margus Avatar asked Sep 29 '10 22:09

Margus


1 Answers

Without testing, the basic transcription would be something like this:

Shift =: (33 b.)
And   =: (17 b.)
Not   =: (26 b.)
Xor   =: (22 b.)
Or    =: (23 b.)

BastardFunction =: 3 : 0
  a =. (Not y) And (_1 Shift (Not y))
  if. a do.
    b =. a  Xor (a And a - 1)
    (1 Shift b) Or b
  else.
    0
  end.
)

But there could be a smarter approach.

like image 183
MPelletier Avatar answered Sep 28 '22 01:09

MPelletier