Colin Cross | 7bb052a | 2015-02-03 12:59:37 -0800 | [diff] [blame^] | 1 | // Copyright 2011 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package binary_test |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "encoding/binary" |
| 10 | "fmt" |
| 11 | "math" |
| 12 | ) |
| 13 | |
| 14 | func ExampleWrite() { |
| 15 | buf := new(bytes.Buffer) |
| 16 | var pi float64 = math.Pi |
| 17 | err := binary.Write(buf, binary.LittleEndian, pi) |
| 18 | if err != nil { |
| 19 | fmt.Println("binary.Write failed:", err) |
| 20 | } |
| 21 | fmt.Printf("% x", buf.Bytes()) |
| 22 | // Output: 18 2d 44 54 fb 21 09 40 |
| 23 | } |
| 24 | |
| 25 | func ExampleWrite_multi() { |
| 26 | buf := new(bytes.Buffer) |
| 27 | var data = []interface{}{ |
| 28 | uint16(61374), |
| 29 | int8(-54), |
| 30 | uint8(254), |
| 31 | } |
| 32 | for _, v := range data { |
| 33 | err := binary.Write(buf, binary.LittleEndian, v) |
| 34 | if err != nil { |
| 35 | fmt.Println("binary.Write failed:", err) |
| 36 | } |
| 37 | } |
| 38 | fmt.Printf("%x", buf.Bytes()) |
| 39 | // Output: beefcafe |
| 40 | } |
| 41 | |
| 42 | func ExampleRead() { |
| 43 | var pi float64 |
| 44 | b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40} |
| 45 | buf := bytes.NewReader(b) |
| 46 | err := binary.Read(buf, binary.LittleEndian, &pi) |
| 47 | if err != nil { |
| 48 | fmt.Println("binary.Read failed:", err) |
| 49 | } |
| 50 | fmt.Print(pi) |
| 51 | // Output: 3.141592653589793 |
| 52 | } |