Non-decimal radices/Input: Difference between revisions

→‎{{header|Go}}: Use Sscanf rather than a bytes.Buffer, the comment already indicates Fscanf is more common; io.Reader vs file in comment; mention fmt scanning can work with any type and show it with big.Int
(Add Nimrod)
(→‎{{header|Go}}: Use Sscanf rather than a bytes.Buffer, the comment already indicates Fscanf is more common; io.Reader vs file in comment; mention fmt scanning can work with any type and show it with big.Int)
Line 326:
 
import (
"bytes"
"fmt"
"math/big"
Line 340 ⟶ 339:
// ParseInt handles arbitrary bases from 2 to 36, and returns
// a result of the requested size (64 bits shown here.)
// If the base argument is zero the base is determined by prefix
// as with math/big below.
x64, _ := strconv.ParseInt("3c2", 19, 64)
fmt.Println(x64)
 
// package bytes+fmt: allows direct conversion from strings, standard
// toinput, integeror typesfrom foran basesio.Reader 2(file, 8buffer, 10,etc) andto 16.integer types
// (Fscanffor bases 2, 8, 10, and scanf16 areor moreto commonany fortype that readingimplements fromthe
// fmt.Scanner interface (e.g. a big.Int).
// files or stdin than for reading from strings.)
// (Fscanf and Scanf are more common for reading from
fmt.Fscanf(bytes.NewBufferString("1101"), "%b", &x)
// filesan io.Reader or stdin than Sscanf for reading from strings.)
fmt.Fscanf(bytes.NewBufferStringSscanf("1101"), "%b", &x)
fmt.Println(x)
 
fmt.Fscanf(bytes.NewBufferStringSscanf("15"), "%o", &x)
fmt.Println(x)
 
fmt.Fscanf(bytes.NewBufferStringSscanf("13"), "%d", &x)
fmt.Println(x)
 
fmt.Fscanf(bytes.NewBufferStringSscanf("d"), "%x", &x)
fmt.Println(x)
 
// package math/big: allows conversion from string to big integer.
// any base from 2 to 16 can be specified as second parameter.
var z big.Int
Line 376 ⟶ 379:
 
z.SetString("0xd", 0) // 0x -> base 16
fmt.Println(&z)
 
// As mentioned, a big.Int (or any type implementing fmt.Scanner)
// can also be use with any of the fmt scanning functions.
fmt.Sscanf("15", "%o", &z)
fmt.Println(&z)
}</lang>
Anonymous user