a simple PNG decoder in Go

while working with image files, I needed a simple way to analyze content of a picture; so I wrote this tool that “walks” inside a PNG file and reports all the chunks seen; this is intended to be expanded with more features in a future. package main import ( "encoding/binary" "fmt" "io" "os" ) type chunk struct { Length uint32 ChunkType [4]byte } func main() { if len(os.Args) != 2 { fmt.Printf("Usage: %s filename.png\n", os.Args[0]) os.Exit(1) } f, err := os.Open(os.Args[1]) if err != nil { panic(err) } defer f.Close() header := make([]byte, 8) _, err = f.Read(header) fmt.Printf("header: %v\n", header) if err != nil { panic(err) } var data chunk var offset int64 offset = 8 for { err = binary.Read(f, binary.BigEndian, &data) if err != nil { if err == io.EOF { break } panic(err) } fmt.Printf("Offset: %d chunk len=%d, type: %s\n", offset, data.Length, string(data.ChunkType[:4])) f.Seek(int64(data.Length+4), io.SeekCurrent) offset += int64(data.Length) + 4 } } usage: ...

January 28, 2018 · Andrea Manzini

convert a binary file to ascii using hexdump

I have a binary file with data stored as two-byte big-endian 16-bit words. We need to extract the values in the file and print them in decimal ASCII format, so to obtain numbers in the 0-655535 range. let’s create the sample file: $ echo -en "\x01\x02\x03\x04\x05\x06\x07\x08" > file.bin and show its content in binary form: $ hexdump -C file.bin 00000000 01 02 03 04 05 06 07 08 |........| 00000008 to get the desired output we can use the powerful, but little documented format string option of hexdump: ...

October 20, 2016 · Andrea Manzini