2

big.Intaをシンプルな base32に変換したい。zBase32やCrockfordによって実装されたRFC 4648のような標準的な base32 のものではなく、文字 0-9A-V 文字セットごとに単純な通常の 5 ビットだけが必要です。base32

私はbase32パッケージを知っていますが、それは私が望んでいることをしません - それはパディングと私が望まないものを使って標準の32進法で結果を構築します。確かにそれを使用して、末尾の「=」文字を切り離し、残ったものをハックすることはできますが、それは残忍な解決策のように思えます。

base32 数値を文字列形式で解析できる がありますが、逆はありません。これは、Javabig.SetString(string, base)のように、私が本当に探しているものです。big.GetString(base)BigInteger.toString(int base)

ただし、まさに私が望むことをnat.string行うa があります。どうすればアクセスできますか?

正しいで自明に呼び出すbig実装を手動で拡張できる方法はありますか?big.GetString(base)nat.stringcharset

big.natbig使用して呼び出す非エクスポートに到達する方法はありますnat.stringか?

他にできることはありますか?

PS私も使用に興味がありますnat.trailingZeroBits-これがすでに行われていることに気付いていなかったので、自分で作成する必要がありました。

4

3 に答える 3

1

go-nutsスレッドに投稿しました。彼らは私の提案に満足しているようです。

一方-Base32の私の実装(記号を処理しません-のようにnat

// The digits
const charset string = "0123456789ABCDEFGHIJKLMNOPQRSTUV"

/*
 Convert the big to base32
*/
func Base32(n big.Int) string {
    // The bytes of the number
    bytes := n.Bytes()
    nBytes := len(bytes)
    if nBytes == 0 {
        // Special case 0.
        return "0"
    }
    // How many digits will be in the string?
    nBits := nBytes * 8
    nDigits := nBits / 5
    if nBits%5 > 0 {
        nDigits += 1
    }
    // Grow the digits into an array
    digits := make([]byte, nDigits)
    digit := nDigits - 1
    // Peel off 5 bits from the array each time.
    for b, shr := nBytes-1, uint(0); b >= 0; {
        // The next lot is there.
        shrp5 := shr + 5
        // Build my bits.
        x := (bytes[b] >> shr)
        if shrp5 > 8 && b > 0 {
            of := shrp5 - 8
            // Add in some bits from the next byte too.
            x &= (1 << (8 - shr)) - 1
            x |= bytes[b-1] << (5 - of)
        }
        // Shift 5 more.
        shr = shrp5
        // Should we step to next byte?
        if shr >= 8 {
            // Next byte
            shr -= 8
            b -= 1
        }
        x &= 0x1f
        // Build my digit
        digits[digit] = charset[x]
        digit -= 1
    }
    // Skip leading zeros.
    lz := 0
    for digits[lz] == '0' {
        lz += 1
    }
    // Return the string equivalent.
    return string(digits[lz:])
}

コメント歓迎。

于 2013-10-08T23:13:57.023 に答える