Non-decimal radices/Input: Difference between revisions

Content added Content deleted
(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: Line 326:


import (
import (
"bytes"
"fmt"
"fmt"
"math/big"
"math/big"
Line 340: Line 339:
// ParseInt handles arbitrary bases from 2 to 36, and returns
// ParseInt handles arbitrary bases from 2 to 36, and returns
// a result of the requested size (64 bits shown here.)
// 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)
x64, _ := strconv.ParseInt("3c2", 19, 64)
fmt.Println(x64)
fmt.Println(x64)


// package bytes+fmt: allows direct conversion from strings
// package fmt: allows direct conversion from strings, standard
// to integer types for bases 2, 8, 10, and 16.
// input, or from an io.Reader (file, buffer, etc) to integer types
// (Fscanf and scanf are more common for reading from
// for bases 2, 8, 10, and 16 or to any type that implements the
// 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)
// an io.Reader or stdin than Sscanf for reading from strings.)
fmt.Sscanf("1101", "%b", &x)
fmt.Println(x)
fmt.Println(x)


fmt.Fscanf(bytes.NewBufferString("15"), "%o", &x)
fmt.Sscanf("15", "%o", &x)
fmt.Println(x)
fmt.Println(x)


fmt.Fscanf(bytes.NewBufferString("13"), "%d", &x)
fmt.Sscanf("13", "%d", &x)
fmt.Println(x)
fmt.Println(x)


fmt.Fscanf(bytes.NewBufferString("d"), "%x", &x)
fmt.Sscanf("d", "%x", &x)
fmt.Println(x)
fmt.Println(x)


// package big: allows conversion from string to big integer.
// package math/big: allows conversion from string to big integer.
// any base from 2 to 16 can be specified as second parameter.
// any base from 2 to 16 can be specified as second parameter.
var z big.Int
var z big.Int
Line 376: Line 379:


z.SetString("0xd", 0) // 0x -> base 16
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)
fmt.Println(&z)
}</lang>
}</lang>