Last active
February 5, 2016 11:43
-
-
Save scottcagno/506c6fea55f200d19a9e to your computer and use it in GitHub Desktop.
Encode a uint32 into a byte slice, write it to disk, and read it from disk.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/binary" | |
| "io/ioutil" | |
| "log" | |
| "fmt" | |
| ) | |
| const ( | |
| max_uint8 uint8 = 255 // 1 byte min | |
| max_uint16 uint16 = 65535 // 2 byte min | |
| max_uint32 uint32 = 4294967295 // 4 byte min | |
| max_uint64 uint64 = 18446744073709551615 // 8 byte min | |
| ) | |
| func main() { | |
| fmt.Printf("Writing to disk, "); test32() | |
| if err := ioutil.WriteFile("test", v, 0666); err != nil { | |
| log.Println(err) | |
| } | |
| if b, err := ioutil.ReadFile("test"); err != nil { | |
| log.Println(err) | |
| } else { | |
| fmt.Println("Read from disk,", b) | |
| } | |
| test16() | |
| test32() | |
| test64() | |
| } | |
| func test16() { | |
| bs := make([]byte, 2) | |
| binary.LittleEndian.PutUint16(bs, max_uint16) | |
| fmt.Println(bs) | |
| } | |
| func decUint16(b []byte) uint16 { | |
| return uint16(b[0]) | uint16(b[1]) << 8 | |
| } | |
| func test32() { | |
| bs := make([]byte, 4) | |
| binary.LittleEndian.PutUint32(bs, max_uint32) | |
| fmt.Println(bs) | |
| } | |
| func test64() { | |
| bs := make([]byte, 8) | |
| binary.LittleEndian.PutUint64(bs, max_uint64) | |
| fmt.Println(bs) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment