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
+11.3k Golang : Fuzzy string search or approximate string matching example
+18.2k Golang : Find IP address from string
+12.3k Golang : HTTP response JSON encoded data
+10.1k Android Studio : Simple input textbox and intercept key example
+41.1k Golang : Convert string to array/slice
+11.8k Golang : Get remaining text such as id or filename after last segment in URL path
+6.7k Golang : Find the shortest line of text example
+30.5k Golang : Interpolating or substituting variables in string examples
+11.9k Golang : List running EC2 instances and descriptions
+15.3k Golang : Get digits from integer before and after given position example
+17.7k Golang : Put UTF8 text on OpenCV video capture image frame
+15.8k Golang : How to check if input from os.Args is integer?