Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added base/1 and unbase/1 #2241

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Added base/1 and unbase/1 #2241

wants to merge 4 commits into from

Conversation

ghost
Copy link

@ghost ghost commented Jan 3, 2021

Base conversion functions get re-implemented quite frequently, thus they deserve their own built-ins.

base/1 takes an operand x and converts the input to base x. Example usage:

14 | base(2)  -> [1, 1, 1, 0]

unbase/1 is the opposite of base/1: it takes an operand x and converts the input from base x. Example usage:

[1, 1, 1, 0] | unbase(2) -> 14

@coveralls
Copy link

coveralls commented Jan 3, 2021

Coverage Status

Coverage increased (+0.4%) to 84.494% when pulling 0d872a8 on 2x-1:master into 80052e5 on stedolan:master.

src/builtin.jq Outdated Show resolved Hide resolved
@odnoletkov
Copy link

In my experience it is more convenient to work with this representation of numbers – array of base digits – when order of digits is reversed. So the lowest order digit is the first and highest is the last in the array:

14 | base(2)  -> [0, 1, 1, 1]

That way when implementing operations with multiple numbers same order digits match naturally, for example:

def bitwiseand($a; $b): [$a, $b] | transpose | map(if all(. > 0) then 1 else 0 end);

For the names what do you think about tobase/1 and frombase/1? This follows convention set by other APIs in the standard library.


Lastly, we need to document these in the manual.

@itchyny
Copy link
Contributor

itchyny commented Jan 7, 2021

Lastly, we need to document these in the manual.

And tests, too.

@ghost
Copy link
Author

ghost commented Jan 15, 2021

@odnoletkov Sorry for the inactivity. These are all good suggestions, I'll be trying to fullfill them.

@ghost
Copy link
Author

ghost commented Jan 15, 2021

@itchyny Not sure where the tests are though - I'm relatively new to jq's source code.

@tst2005
Copy link

tst2005 commented Apr 23, 2021

I think there is a bug in frombase.

-def frombase($a): reduce (.[] | reverse) as $i (0; . * $a + $i);
+def frombase($a): reduce (reverse | .[]) as $i (0; . * $a + $i);

@tst2005
Copy link

tst2005 commented Aug 27, 2021

in tobase, there is an issue but only when the input value is 0.
jq -n '0|tobase(16)' shoule be [0] not []

-def tobase($a): [while(. > 0; (. / $a) | floor) % $a];
+def tobase($a): [while(. > 0; (. / $a) | floor) % $a]|if .==[] then [0] else . end;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants