本文整理汇总了Golang中math/big.Int.SetString方法的典型用法代码示例。如果您正苦于以下问题:Golang Int.SetString方法的具体用法?Golang Int.SetString怎么用?Golang Int.SetString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math/big.Int
的用法示例。
在下文中一共展示了Int.SetString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CompileInstr
// Compile instruction
//
// Attempts to compile and parse the given instruction in "s"
// and returns the byte sequence
func CompileInstr(s interface{}) ([]byte, error) {
switch s.(type) {
case string:
str := s.(string)
isOp := IsOpCode(str)
if isOp {
return []byte{OpCodes[str]}, nil
}
// Check for pre formatted byte array
// Jumps are preformatted
if []byte(str)[0] == 0 {
return []byte(str), nil
}
num := new(big.Int)
_, success := num.SetString(str, 0)
// Assume regular bytes during compilation
if !success {
num.SetBytes([]byte(str))
}
return num.Bytes(), nil
case int:
//num := bigToBytes(big.NewInt(int64(s.(int))), 256)
return big.NewInt(int64(s.(int))).Bytes(), nil
case []byte:
return new(big.Int).SetBytes(s.([]byte)).Bytes(), nil
}
return nil, nil
}
示例2: TestDecryptOAEP
func TestDecryptOAEP(t *testing.T) {
random := rand.Reader
sha1 := sha1.New()
n := new(big.Int)
d := new(big.Int)
for i, test := range testEncryptOAEPData {
n.SetString(test.modulus, 16)
d.SetString(test.d, 16)
private := new(PrivateKey)
private.PublicKey = PublicKey{n, test.e}
private.D = d
for j, message := range test.msgs {
out, err := DecryptOAEP(sha1, nil, private, message.out, nil)
if err != nil {
t.Errorf("#%d,%d error: %s", i, j, err)
} else if !bytes.Equal(out, message.in) {
t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
}
// Decrypt with blinding.
out, err = DecryptOAEP(sha1, random, private, message.out, nil)
if err != nil {
t.Errorf("#%d,%d (blind) error: %s", i, j, err)
} else if !bytes.Equal(out, message.in) {
t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
}
}
if testing.Short() {
break
}
}
}
示例3: main
func main() {
in, _ := os.Open("465.in")
defer in.Close()
out, _ := os.Create("465.out")
defer out.Close()
var s1, s2 string
var op byte
var i1, i2, i3 big.Int
var maxInt = big.NewInt(math.MaxInt32)
for {
if _, err := fmt.Fscanf(in, "%s %c %s", &s1, &op, &s2); err != nil {
break
}
fmt.Fprintf(out, "%s %c %s\n", s1, op, s2)
i1.SetString(s1, 10)
if i1.Cmp(maxInt) > 0 {
fmt.Fprintln(out, "first number too big")
}
i2.SetString(s2, 10)
if i2.Cmp(maxInt) > 0 {
fmt.Fprintln(out, "second number too big")
}
if op == '+' {
i3.Add(&i1, &i2)
} else {
i3.Mul(&i1, &i2)
}
if i3.Cmp(maxInt) > 0 {
fmt.Fprintln(out, "result too big")
}
}
}
示例4: main
func main() {
var iban string
var r, s, t, st []string
u := new(big.Int)
v := new(big.Int)
w := new(big.Int)
iban = "GB82 TEST 1234 5698 7654 32"
r = strings.Split(iban, " ")
s = strings.Split(r[0], "")
t = strings.Split(r[1], "")
st = []string{strconv.Itoa(sCode[t[0]]),
strconv.Itoa(sCode[t[1]]),
strconv.Itoa(sCode[t[2]]),
strconv.Itoa(sCode[t[3]]),
strings.Join(r[2:6], ""),
strconv.Itoa(sCode[s[0]]),
strconv.Itoa(sCode[s[1]]),
strings.Join(s[2:4], ""),
}
u.SetString(strings.Join(st, ""), 10)
v.SetInt64(97)
w.Mod(u, v)
if w.Uint64() == 1 && lCode[strings.Join(s[0:2], "")] == len(strings.Join(r, "")) {
fmt.Printf("IBAN %s looks good!\n", iban)
} else {
fmt.Printf("IBAN %s looks wrong!\n", iban)
}
}
示例5: q2
func q2() {
n := new(big.Int)
a := new(big.Int)
asquared := new(big.Int)
one := new(big.Int)
x := new(big.Int)
xsquared := new(big.Int)
p := new(big.Int)
q := new(big.Int)
candidate := new(big.Int)
n.SetString("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 10)
one.SetString("1", 10)
a = mathutil.SqrtBig(n)
for {
a.Add(a, one)
asquared.Mul(a, a)
xsquared.Sub(asquared, n)
x = mathutil.SqrtBig(xsquared)
p.Sub(a, x)
q.Add(a, x)
if candidate.Mul(p, q).Cmp(n) == 0 {
fmt.Println(p.String())
break
}
}
}
示例6: main
func main() {
var a, b string
fmt.Scan(&a, &b)
start := time.Now()
/** SetString(a string,base int)-----将输入的字符串处理为BigInt
** The base argument must be 0 or a value from 2 through MaxBase.
** If the base is 0,the string prefix determines the actual conversion base.
** A prefix of “0x” or “0X” selects base 16;
** the “0” prefix selects base 8, and a “0b” or “0B” prefix selects
** base 2. Otherwise the selected base is 10.
** 例如:输入的字符串为"1234...",表示该字符串为10进制,base=10;
** 输入的字符串为"0x10ac1...",表示该字符串为16进制,base=16
** base开始取0时,当输入的字符串为"0x101...",前缀为"0x",表示该字符串为16
** 进制,所以base的实际值为16
**/
c := new(big.Int)
d := new(big.Int)
e := new(big.Int)
c.SetString(a, 10)
d.SetString(b, 10)
e.Mul(c, d)
fmt.Println(e)
duration := time.Since(start)
fmt.Printf(" %vms\n", duration.Seconds()*1000)
}
示例7: main
func main() {
// Open file for read
fd, err := os.Open("numbers.txt")
chk(err)
defer fd.Close()
// Line by line reader
scanner := bufio.NewScanner(fd)
scanner.Split(bufio.ScanLines)
// Use standart library - big Integers
bigSum := new(big.Int)
for scanner.Scan() {
ns := scanner.Text()
bigInt := new(big.Int)
bigInt.SetString(ns, 10) // Convert readed decimal string to big.Int
bigSum.Add(bigSum, bigInt)
}
answerString := bigSum.String()
fmt.Println("Result:", answerString, len(answerString))
fmt.Println("Answer:", answerString[0:10])
}
示例8: makeDecimalFromMandE
// makeDecimalFromMandE reconstructs the decimal from the mantissa M and
// exponent E.
func makeDecimalFromMandE(negative bool, e int, m []byte, tmp []byte) decimal.Decimal {
// ±dddd.
b := tmp[:0]
if n := len(m)*2 + 1; cap(b) < n {
b = make([]byte, 0, n)
}
if negative {
b = append(b, '-')
}
for i, v := range m {
t := int(v)
if i == len(m) {
t--
}
t /= 2
b = append(b, byte(t/10)+'0', byte(t%10)+'0')
}
// We unsafely convert the []byte to a string to avoid the usual allocation
// when converting to a string.
bi := new(big.Int)
bi, ok := bi.SetString(*(*string)(unsafe.Pointer(&b)), 10)
if !ok {
panic("could not set big.Int's string value")
}
exp := 2*e - len(b)
if negative {
exp++
}
return decimal.NewFromBigInt(bi, int32(exp))
}
示例9: problem55
func problem55() string {
reverseBig := func(b *big.Int) *big.Int {
str := b.String()
lenStr := len(str)
strRev := make([]rune, lenStr)
for i, r := range str {
strRev[lenStr-1-i] = r
}
bReversed := new(big.Int)
bReversed.SetString(string(strRev), 10)
return bReversed
}
count := 0
const iMax, jMax = 10000, 51
for i := 1; i < iMax; i++ {
ib := NewBig(i)
count++
for j := 0; j < jMax; j++ {
ib.Add(ib, reverseBig(ib)) // compute next Lychrel
if IsBigPalindrome(ib) {
count--
break
}
}
}
return itoa(count)
}
示例10: main
func main() {
in, _ := os.Open("10183.in")
defer in.Close()
out, _ := os.Create("10183.out")
defer out.Close()
var a, b string
var n1, n2 big.Int
l := len(p)
for {
if fmt.Fscanf(in, "%s%s", &a, &b); a == "0" && b == "0" {
break
}
n1.SetString(a, 10)
n2.SetString(b, 10)
c := 0
for i := 1; i < l; i++ {
if p[i].Cmp(&n1) >= 0 && p[i].Cmp(&n2) <= 0 {
c++
}
if p[i].Cmp(&n2) > 0 {
break
}
}
fmt.Fprintln(out, c)
}
}
示例11: NewFromString
// NewFromString returns a new Decimal from a string representation.
//
// Example:
//
// d, err := NewFromString("-123.45")
// d2, err := NewFromString(".0001")
//
func NewFromString(value string) (Decimal, error) {
var intString string
var exp int32
parts := strings.Split(value, ".")
if len(parts) == 1 {
// There is no decimal point, we can just parse the original string as
// an int
intString = value
exp = 0
} else if len(parts) == 2 {
intString = parts[0] + parts[1]
expInt := -len(parts[1])
if expInt < math.MinInt32 {
// NOTE(vadim): I doubt a string could realistically be this long
return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", value)
}
exp = int32(expInt)
} else {
return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value)
}
dValue := new(big.Int)
_, ok := dValue.SetString(intString, 10)
if !ok {
return Decimal{}, fmt.Errorf("can't convert %s to decimal", value)
}
return Decimal{
value: dValue,
exp: exp,
}, nil
}
示例12: MakeConst
// MakeConst makes an ideal constant from a literal
// token and the corresponding literal string.
func MakeConst(tok token.Token, lit string) Const {
switch tok {
case token.INT:
var x big.Int
_, ok := x.SetString(lit, 0)
assert(ok)
return Const{&x}
case token.FLOAT:
var y big.Rat
_, ok := y.SetString(lit)
assert(ok)
return Const{&y}
case token.IMAG:
assert(lit[len(lit)-1] == 'i')
var im big.Rat
_, ok := im.SetString(lit[0 : len(lit)-1])
assert(ok)
return Const{cmplx{big.NewRat(0, 1), &im}}
case token.CHAR:
assert(lit[0] == '\'' && lit[len(lit)-1] == '\'')
code, _, _, err := strconv.UnquoteChar(lit[1:len(lit)-1], '\'')
assert(err == nil)
return Const{big.NewInt(int64(code))}
case token.STRING:
s, err := strconv.Unquote(lit)
assert(err == nil)
return Const{s}
}
panic("unreachable")
}
示例13: TestJwksSerializationPadding
func TestJwksSerializationPadding(t *testing.T) {
x := new(big.Int)
y := new(big.Int)
e := &EssentialHeader{}
e.KeyType = jwa.EC
x.SetString("123520477547912006148785171019615806128401248503564636913311359802381551887648525354374204836279603443398171853465", 10)
y.SetString("13515585925570416130130241699780319456178918334914981404162640338265336278264431930522217750520011829472589865088261", 10)
pubKey := &ecdsa.PublicKey{
Curve: elliptic.P384(),
X: x,
Y: y,
}
jwkPubKey := NewEcdsaPublicKey(pubKey)
jwkPubKey.EssentialHeader = e
jwkJSON, err := json.Marshal(jwkPubKey)
if !assert.NoError(t, err, "JWK Marshalled") {
return
}
_, err = Parse(jwkJSON)
if !assert.NoError(t, err, "JWK Parsed") {
return
}
}
示例14: TestGenerateGUID
func TestGenerateGUID(t *testing.T) {
idReader = rand.New(rand.NewSource(0))
for i := 0; i < 1000; i++ {
guid := NewID()
var i big.Int
_, ok := i.SetString(guid, randomIDBase)
if !ok {
t.Fatal("id should be base 36", i, guid)
}
// To ensure that all identifiers are fixed length, we make sure they
// get padded out to 25 characters, which is the maximum for the base36
// representation of 128-bit identifiers.
//
// For academics, f5lxx1zz5pnorynqglhzmsp33 == 2^128 - 1. This value
// was calculated from floor(log(2^128-1, 36)) + 1.
//
// See http://mathworld.wolfram.com/NumberLength.html for more information.
if len(guid) != maxRandomIDLength {
t.Fatalf("len(%s) != %v", guid, maxRandomIDLength)
}
}
}
示例15: main
func main() {
var s string
var n, two, tmp big.Int
two.SetInt64(2)
in, _ := os.Open("10519.in")
defer in.Close()
out, _ := os.Create("10519.out")
defer out.Close()
for {
if _, err := fmt.Fscanf(in, "%s", &s); err != nil {
break
}
if s == "0" {
fmt.Fprintln(out, 1)
continue
}
n.SetString(s, 10)
tmp.Mul(&n, &n)
tmp.Sub(&tmp, &n)
tmp.Add(&tmp, &two)
fmt.Fprintln(out, &tmp)
}
}