2

I want to convert any positive integer to some base from 2 to 9. The output for base 2should be:

0  -> enlist 0
1  -> enlist 1
31 -> 1 1 1 1 1
62 -> 1 1 1 1 1 0
63 -> 1 1 1 1 1 1
64 -> 1 0 0 0 0 0 0

I developed the next function for this

convertToBase: reverse {[x;base;result] 
    result,: `int$x mod base; 
    x-: last result; 
    x%: base; 
    $[x=0;result;.z.s[x;base;result]]
};

//invocation
convertToBase[62;2;()]

The question is, if there is any build-in Q function to do it effectively? If not, how above solution can be optimized?

Anton Dovzhenko
  • 2,399
  • 11
  • 16

1 Answers1

3

The vs function does this if the left-hand argument is a number.

For example:

2 vs 100

will return:

1 1 0 0 1 0 0

In the case where you have 0 as the right-hand argument it will, however, return an empty list, but you can wrap it with a conditional that outputs ,0 in the event that the returned value is empty.

Paul Kerrigan
  • 465
  • 5
  • 12