Golang : Convert file content to Hex
Somehow for the last couple of days I keep on thinking about my childhood days of hacking DOS games with Central Point PC-Tools Hex Editors. Couple of games that I remember pretty well are the BattleTech CPRG and Ultima 6. The hacks usually involve unlocking new weapons, adding ammo and money. Occasionally I will use the Hex editor to view the signatures of some virus authors or try to see if the EXE file is created by Borland or Microsoft compiler.
Feeling itchy and wanting to relive my childhood days again. I have written a simple Go program to convert a file content into hex codes.
readfiletohex.go
package main
import (
"fmt"
"os"
"bufio"
)
func main () {
file, err := os.Open("dummy.txt")
if err != nil {
panic(err.Error())
}
defer file.Close()
reader := bufio.NewReader(file)
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanRunes)
var finalResult []string
var finalOriginal []string
for scanner.Scan() {
original := fmt.Sprintf("%s ", scanner.Text())
finalOriginal = append(finalOriginal, original)
hexstring := fmt.Sprintf("%x ", scanner.Text())
finalResult = append(finalResult, hexstring)
}
fmt.Println("Data from file : ")
fmt.Println(finalOriginal)
fmt.Println("Converted to Hex : ")
fmt.Println(finalResult)
}
and populate the dummy.txt file with
MZ
ABCDEFG
12345678
!@#$%^&*()
reliving the 80s!
and when execute :
>go run readfiletohex.go
the output will be
Data from file :
[M Z
A B C D E F G
1 2 3 4 5 6 7 8
! @ # $ % ^ & * ( )
r e l i v i n g t h e 8 0 s !
]
Converted to Hex :
[4d 5a 0a 41 42 43 44 45 46 47 0a 31 32 33 34 35 36 37 38 0a 21 40 23 24 25 5e 26 2a 28 29 0a 72 65 6c 69 76 69 6e 67 20 74 68 65 20 38 30 73 21 0a ]
Of course, I could have spend more time tidying up the output or build a complete Hex editor. But I will leave to you reader to finish the job :-)
Hope this tutorial can be helpful to others.
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.7k Google : Block or disable caching of your website content
+9.8k Golang : Identifying Golang HTTP client request
+11k Golang : How to pipe input data to executing child process?
+12.8k Swift : Convert (cast) Int to String ?
+17.4k Convert JSON to CSV in Golang
+22.6k Golang : Calculate time different
+39.2k Golang : Remove dashes(or any character) from string
+6.3k PHP : Shuffle to display different content or advertisement
+25.5k Golang : missing Mercurial command
+16k Golang : convert string or integer to big.Int type
+11.1k Golang : How to flush a channel before the end of program?
+6k Golang : Calculate US Dollar Index (DXY)