Created
November 17, 2019 22:33
-
-
Save Ushiosan23/172d6d418c0584d11a5e272282ed97dc to your computer and use it in GitHub Desktop.
Write file with binary data. Golang.
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 ( | |
| "bytes" | |
| "encoding/gob" | |
| "fmt" | |
| "io/ioutil" | |
| "os" | |
| "path/filepath" | |
| ) | |
| // Pixel struct | |
| type Pixel struct { | |
| X, Y int | |
| R, G, B, A byte | |
| } | |
| func main() { | |
| var currentDir, _ = filepath.Abs(filepath.Dir(os.Args[0])) | |
| var file = filepath.Join(currentDir, "data.pixel") | |
| var open, _ = os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0777) | |
| /* Write binary data */ | |
| var buff bytes.Buffer | |
| var pixel []Pixel | |
| var max = 20 | |
| for x := 0; x < max; x++ { | |
| for y := 0; y < max ; y++ { | |
| var r = byte(math.Floor(float64(rand.Float32() * 255))) | |
| var g = byte(math.Floor(float64(rand.Float32() * 255))) | |
| var b = byte(math.Floor(float64(rand.Float32() * 255))) | |
| pixel = append(pixel, Pixel{x, y, r, g, b, 255}) | |
| } | |
| } | |
| var enc = gob.NewEncoder(&buff) | |
| _ = enc.Encode(pixel) | |
| _, _ = open.Write(buff.Bytes()) | |
| _ = open.Close() | |
| /* Read binary data */ | |
| var read, _ = ioutil.ReadFile(file) | |
| var data = bytes.NewBuffer(read) | |
| var dec = gob.NewDecoder(data) | |
| var r = make([]Pixel, 50 * 50) | |
| _ = dec.Decode(&r) | |
| fmt.Println(r) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment