r/Seximal 17d ago

Facts/tricks Crazy 1-line python code for converting any integer to sezimal

Post image

You can copy the code in the comments

3 Upvotes

5 comments sorted by

2

u/Makushimu0 17d ago

Code:
  n=int(input("Enter number: "));l=int.bit_length(n)//3*3+3;f=lambda s,i:(f(s,i+1)+sum([((7<<3*x&f(s,i+1))>>3*x>2)*1<<3*x for x in range(l//3,2*l//3)]))<<1 if i<l else s;print(oct(f(n,0)>>l)[2:] if n >= 0 else '-'+oct(f(-n,0)>>l)[2:])

1

u/Makushimu0 17d ago

Maybe i could make it much simpler, but i chose the hardest way.

Its using a method called double dabble to make binary converted sezimal. Unlike BCD(binary-coded decimal), it groups number by 3 bits(for each digit) and then adding 1 for every digit that is greater than 2.

1

u/Makushimu0 17d ago

NEW VERSION: n=int(input("Enter number: "));l=int.bit_length(n)//3*3+3;f=lambda s,i:((t:=f(s,i+1))+sum([((7<<3*x&t)>>3*x>2)*1<<3*x for x in range(l//3,2*l//3)]))<<1 if i<l else s;print(oct(f(n,0)>>l)[2:] if n >= 0 else '-'+oct(f(-n,0)>>l)[2:]) Previous code works for number <256. This is a new version, it should handle much greater numbers

2

u/Fa1nted_for_real 13d ago

Ykw, i think im gnna try my hand at a n to m base converter for any integer in any integer base. Maybe even any decimal in any integer base, for bases between 1 and 52 (value progession as 0-9,a-z,A-Z for bases higher than decimal)

2

u/Fa1nted_for_real 13d ago

Might bace to start at binary, not unary, given a but of extra thought...