Base-n digits for a given value

Here is the function that I use to create a UInt64 result from an array of numbers and a base value.

function BaseNToInteger(const ABase: Cardinal; const ADigits: Array of Byte): UInt64; var i: Integer; begin Result := 0; for i := 0 to (Length(ADigits) - 1) do begin Result := Result + (ADigits[i] * Power(i, ABase)); end; end; 

[Please do not worry about the Power () function; I wrote my own, which uses cardinals and produces UInt64 results.]

This is the easy part.

Since my math skills seem to have rusted over the years, the hard part that I struggle with is these:

1) For a given UInt64 value, how can I create an ADigits array for a given base value (where base> 1)?

2) How to determine the length of the ADigits array for a given base value (where base> 1), which will represent a given UInt64 value?

+4
source share
2 answers

Implementation as functions with dynamic arrays ...

 uses math; type TDigits = Array of Byte; Function BaseNToInteger(const Digits: TDigits; Base: Integer): Cardinal; var i: integer; begin Result := 0; for i := High(Digits) DownTo Low(Digits) do Result := Base * Result + Digits[i]; end; Function IntegerToBaseN(Nr: Cardinal; Base: Integer): TDigits; var i: integer; function CeilAllways(const X: Extended): Integer; begin Result := Integer(Trunc(X)); if Frac(X) >= 0 then Inc(Result); end; begin SetLength(Result, CeilAllways(ln(Nr) / ln(Base))); for i := Low(Result) to High(Result) do begin Result[i] := Nr mod Base; Nr := Nr div Base; end; end; 
+4
source

Following my previous comment, here is the opportunity (compiled but not tested)

 unit BaseConv; interface type TDigits = array[0 .. 63] of uint32; { Recover number from digits, number of digits is in nd } procedure ToInteger(var n: uint32; var digits: TDigits; nd, base: integer); { Compute digits in given base, number of digits is returned in nd } procedure FromInteger(n: uint32; var digits: TDigits; var nd: integer; base: integer); implementation procedure ToInteger(var n: uint32; var digits: TDigits; nd, base: integer); var i: integer; begin n := 0; for i := nd - 1 downto 0 do n := base*n + digits[i]; end; procedure FromInteger(n: uint32; var digits: TDigits; var nd: integer; base: integer); begin nd := 0; repeat digits[nd] := n mod base; n := n div base; nd := nd + 1; until n = 0; end; end. 
+3
source

Source: https://habr.com/ru/post/1480370/


All Articles