func scalar2big(out *big.Int, in *[4]C.ulonglong) { bits := make([]big.Word, 8) for i := 0; i < len(bits); i += 2 { bits[i] = big.Word(in[i>>1] & 0x00000000ffffffff) bits[i+1] = big.Word((in[i>>1] & 0xffffffff00000000) >> 32) } out.SetBits(bits) }
// Credit for this func: Hugo Peixoto (https://github.com/hugopeixoto) func (key *KeyID) add2nModK(n int, k int) *KeyID { words := key.integer.Bits() extended := make([]big.Word, (k+_W-1)/_W) copy(extended, words) for n/_W < k { i := n / _W w := extended[i] new_w := w + (big.Word(1) << uint(n-i*_W)) extended[i] = new_w if new_w < w { n = (i + 1) * _W } else { break } } result := big.NewInt(0).SetBits(extended) hex := fmt.Sprintf("%040x", result) return &KeyID{ hex: hex, integer: result, } }
func scalar2big(out *big.Int, in *[4]C.ulonglong) { bits := make([]big.Word, 4) for i := range bits { bits[i] = big.Word(in[i]) } out.SetBits(bits) }
// MakeFromBytes returns the Int value given the bytes of its little-endian // binary representation. An empty byte slice argument represents 0. func MakeFromBytes(bytes []byte) Value { words := make([]big.Word, (len(bytes)+(wordSize-1))/wordSize) i := 0 var w big.Word var s uint for _, b := range bytes { w |= big.Word(b) << s if s += 8; s == wordSize*8 { words[i] = w i++ w = 0 s = 0 } } // store last word if i < len(words) { words[i] = w i++ } // remove leading 0's for i > 0 && words[i-1] == 0 { i-- } return makeInt(newInt().SetBits(words[:i])) }
// Big produces a uniformly distributed random positive number up to nbits bits // in length. It panics if nbits <= 0. func (r RNG) Big(nbits int) *big.Int { if nbits <= 0 { panic("maximum zero or below") } var p []big.Word if ^big.Word(0) != 0xffffffff { // 64-bit n := nbits >> 6 if nbits&63 != 0 { n++ } p = make([]big.Word, n) for i := range p { p[i] = big.Word(r.Uint64()) } p[0] &= 0xffffffffffffffff >> big.Word(64-nbits&63) } else { // 32-bit n := nbits >> 5 if nbits&31 != 0 { n++ } p = make([]big.Word, n) for i := 1; i < len(p); i += 2 { // Use each value for two words. x := r.Uint64() p[i-1] = big.Word(x) p[i] = big.Word(x >> 32) } p[n-1] = big.Word(r.Uint64()) p[0] &= 0xffffffff >> big.Word(32-nbits&31) } return new(big.Int).SetBits(p) }
// TrailingOnesBig returns the number of trailing 1 bits in v. func TrailingOnesBig(v *big.Int) int { words := v.Bits() for i, b := range words { if b != ^big.Word(0) { return i*wordBits + tzw(^b) } } return len(words) * wordBits }
// reads num into buf as big-endian bytes. func readBits(buf []byte, num *big.Int) { const wordLen = int(unsafe.Sizeof(big.Word(0))) i := len(buf) for _, d := range num.Bits() { for j := 0; j < wordLen && i > 0; j++ { i-- buf[i] = byte(d) d >>= 8 } } }
// Shift computes (x << k) mod (2^n+1). func (z fermat) Shift(x fermat, k int) { if len(z) != len(x) { println(len(z), len(x)) panic("len(z) != len(x) in Shift") } n := len(x) - 1 // Shift by n*_W is taking the opposite. k %= 2 * n * _W if k < 0 { k += 2 * n * _W } neg := false if k >= n*_W { k -= n * _W neg = true } kw, kb := k/_W, k%_W z[n] = 1 // Add (-1) if !neg { for i := 0; i < kw; i++ { z[i] = 0 } // Shift left by kw words. // x = a·2^(n-k) + b // x<<k = (b<<k) - a copy(z[kw:], x[:n-kw]) b := subVV(z[:kw+1], z[:kw+1], x[n-kw:]) if z[kw+1] > 0 { z[kw+1] -= b } else { subVW(z[kw+1:], z[kw+1:], b) } } else { for i := kw + 1; i < n; i++ { z[i] = 0 } // Shift left and negate, by kw words. copy(z[:kw+1], x[n-kw:n+1]) // z_low = x_high b := subVV(z[kw:n], z[kw:n], x[:n-kw]) // z_high -= x_low z[n] -= b } // Add back 1. if z[0] < ^big.Word(0) { z[0]++ } else { addVW(z, z, 1) } // Shift left by kb bits shlVU(z, z, uint(kb)) z.norm() }
func NewConnection(file string, callback uvr1611.PacketCallback) *gpio { pin, err := InitGPIO(file) if err != nil { log.Fatal(err) } packetReceiver := uvr1611.NewPacketReceiver() packetDecoder := uvr1611.NewPacketDecoder(packetReceiver) byteDecoder := uvr.NewByteDecoder(packetDecoder, uvr.NewTimeout(488.0, 0.4)) syncDecoder := uvr1611.NewSyncDecoder(byteDecoder, byteDecoder, uvr.NewTimeout(488.0*2, 0.4)) signal := uvr.NewSignal(syncDecoder) pin_callback := func(pin embd.DigitalPin) { value, read_err := pin.Read() if read_err != nil { fmt.Println(read_err) } else { signal.Consume(big.Word(value)) } } packetReceiver.RegisterCallback(func(packet uvr1611.Packet) { if callback != nil { callback(packet) } // Stop watching the pin and let other threads do their job pin.StopWatching() syncDecoder.Reset() byteDecoder.Reset() packetDecoder.Reset() // Rewatch after 10 seconds again time.AfterFunc(30*time.Second, func() { pin.Watch(embd.EdgeBoth, pin_callback) if err != nil { log.Fatal("Could not watch pin.", err) } }) }) err = pin.Watch(embd.EdgeBoth, pin_callback) if err != nil { log.Fatal("Could not watch pin.", err) } return &gpio{ pin: pin, } }
// Takes a slice of alphabet.Letter and returns the big.Int binary // representation of that sequence. func lettersToBigInt(seq alphabet.Letters) (*big.Int, error) { out := big.NewInt(0) words := make([]big.Word, len(seq)/33+1) for i := range seq { index := alphabet.DNA.IndexOf(seq[len(seq)-i-1]) if index < 0 { return out, fmt.Errorf("Sequence is not a valid DNA sequence at position %d\n", i+1) } else { wordIndex := i / 32 shiftDist := uint(i-wordIndex*32) * 2 words[wordIndex] |= big.Word(index << shiftDist) } } return out.SetBits(words), nil }
// Sub computes substraction mod 2^n+1. func (z fermat) Sub(x, y fermat) fermat { if len(z) != len(x) { panic("Add: len(z) != len(x)") } n := len(y) - 1 b := subVV(z[:n], x[:n], y[:n]) b += y[n] // If b > 0, we need to subtract b<<n, which is the same as adding b. z[n] = x[n] if z[0] <= ^big.Word(0)-b { z[0] += b } else { addVW(z, z, b) } z.norm() return z }
// copyWords was adapted from math/big/nat.go. It writes the value of // nat into buf using big-endian encoding. len(buf) must be >= len(nat)*bigWordSize. func copyWords(buf []byte, nat []big.Word) []byte { // Omit leading zeros from the resulting byte slice, which is both // safe and exactly what big.Int.Bytes() does. See big.nat.setBytes() // and big.nat.norm() for how this is normalized on decoding. leading := true for w := len(nat) - 1; w >= 0; w-- { d := nat[w] for j := bigWordSize - 1; j >= 0; j-- { by := byte(d >> (8 * big.Word(j))) if by == 0 && leading { continue } leading = false buf = append(buf, by) } } return buf }
func (bin *CortexVarBinary) NextKmer() (*colouredKmer.Kmer, error) { kmer := colouredKmer.Kmer{ Int: big.NewInt(0), Coverages: make([]uint32, bin.ColourCount), Edges: make([]uint8, bin.ColourCount), } bits := make([]uint64, bin.wordsPerKmer) err := bin.read(&bits) if err != nil { return &kmer, err } words := make([]big.Word, bin.wordsPerKmer) for i, v := range bits { words[i] = big.Word(v) } kmer.SetBits(words) bin.read(kmer.Coverages) bin.read(kmer.Edges) return &kmer, nil }
func (r *AllocationBitmap) Release(offset int) error { r.lock.Lock() defer r.lock.Unlock() if r.allocated.Bit(offset) == 0 { return nil } r.allocated = r.allocated.SetBit(r.allocated, offset, 0) r.count-- return nil } const ( // Find the size of a big.Word in bytes. notZero = uint64(^big.Word(0)) wordPower = (notZero>>8)&1 + (notZero>>16)&1 + (notZero>>32)&1 wordSize = 1 << wordPower ) // ForEach calls the provided function for each allocated bit. The // AllocationBitmap may not be modified while this loop is running. func (r *AllocationBitmap) ForEach(fn func(int)) { r.lock.Lock() defer r.lock.Unlock() words := r.allocated.Bits() for wordIdx, word := range words { bit := 0 for word > 0 { if (word & 1) != 0 {
return x.val.Sign() case complexVal: return Sign(x.re) | Sign(x.im) case unknownVal: return 1 // avoid spurious division by zero errors default: panic(fmt.Sprintf("%v not numeric", x)) } } // ---------------------------------------------------------------------------- // Support for assembling/disassembling numeric values const ( // Compute the size of a Word in bytes. _m = ^big.Word(0) _log = _m>>8&1 + _m>>16&1 + _m>>32&1 wordSize = 1 << _log ) // Bytes returns the bytes for the absolute value of x in little- // endian binary representation; x must be an Int. func Bytes(x Value) []byte { var t intVal switch x := x.(type) { case int64Val: t = i64toi(x) case intVal: t = x default: panic(fmt.Sprintf("%v not an Int", x))
// Size implements the Datum interface. func (d *DDecimal) Size() uintptr { intVal := d.Dec.UnscaledBig() return unsafe.Sizeof(*d) + uintptr(cap(intVal.Bits()))*unsafe.Sizeof(big.Word(0)) }
nDigits, _ := numDigits(bi, tmp) dec.SetScale(inf.Scale(nDigits)) } // UpperBoundNonsortingDecimalSize returns the upper bound number of bytes // that the decimal will need for the non-sorting encoding. func UpperBoundNonsortingDecimalSize(d *inf.Dec) int { // Makeup of upper bound size: // - 1 byte for the prefix // - maxVarintSize for the exponent // - wordLen for the big.Int bytes return 1 + maxVarintSize + wordLen(d.UnscaledBig().Bits()) } // Taken from math/big/arith.go. const bigWordSize = int(unsafe.Sizeof(big.Word(0))) func wordLen(nat []big.Word) int { return len(nat) * bigWordSize } // copyWords was adapted from math/big/nat.go. It writes the value of // nat into buf using big-endian encoding. len(buf) must be >= len(nat)*bigWordSize. func copyWords(buf []byte, nat []big.Word) []byte { // Omit leading zeros from the resulting byte slice, which is both // safe and exactly what big.Int.Bytes() does. See big.nat.setBytes() // and big.nat.norm() for how this is normalized on decoding. leading := true for w := len(nat) - 1; w >= 0; w-- { d := nat[w] for j := bigWordSize - 1; j >= 0; j-- {
var deBruijn64Bits = []byte{ 0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4, 62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5, 63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11, 54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6, } // TrailingZeros64 returns the number of trailing 0 bits in v. // // If v is 0, it returns 0. func TrailingZeros64(v uint64) byte { return deBruijn64Bits[v&-v*deBruijn64Multiple>>deBruijn64Shift] } // works for 32 and 64 anyway const wordBits = int((^big.Word(0))>>32&1+1) * 32 var tzw func(big.Word) int func init() { switch wordBits { case 32: tzw = func(w big.Word) int { return int(TrailingZeros32(uint32(w))) } case 64: tzw = func(w big.Word) int { return int(TrailingZeros64(uint64(w))) } } } // TrailingZerosBig returns the number of trailing 0 bits in v. // // If v is 0, it returns 0.
// Package flag provides a simple flag utility package utils import ( "math/big" ) // const taken from math/big package const ( _word0 = big.Word(0) _word1 = ^_word0 _logS = _word1>>8&1 + _word1>>16&1 + _word1>>32&1 _S = 1 << _logS _WORDSIZE = _S << 3 ) type Flag struct { N big.Int name string } var zero big.Int // Print Flag's name func (f Flag) String() string { return f.name } // Check that Flags have the same underlying value func (f Flag) Cmp(flag Flag) bool { return f.N.Cmp(&flag.N) == 0
"text/tabwriter" "time" ) var ( bench = flag.Bool("bench", false, "run benchmarks") half = flag.Bool("half", false, "use half-digit addition") opt = flag.Bool("opt", false, "optimize memory usage") short = flag.Bool("short", false, "only print first 10 digits of result") ) // A large natural number is represented by a nat, each "digit" is // a big.Word; the value zero corresponds to the empty nat slice. type nat []big.Word const W = 1 << (5 + ^big.Word(0)>>63) // big.Word size in bits // The following methods are extracted from math/big to make this a // stand-alone program that can easily be run without dependencies // and compiled with different compilers. func (z nat) make(n int) nat { if n <= cap(z) { return z[:n] // reuse z } // Choosing a good value for e has significant performance impact // because it increases the chance that a value can be reused. const e = 4 // extra capacity return make(nat, n, n+e) }