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
+9.9k Golang : Intercept and process UNIX signals example
+10.5k Golang : Verify Linux user password again before executing a program example
+9.3k Golang : Generate random integer or float number
+7.4k Golang : Generate Datamatrix barcode
+15.9k Golang : Check if IP address is version 4 or 6
+15.4k Golang : File path independent of Operating System
+9.5k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+8.2k Golang : does not implement flag.Value (missing Set method)
+8.8k Golang : Check a web page existence with HEAD request example
+11.1k Golang : calculate elapsed run time
+5.7k Get Facebook friends working in same company
+9.7k Golang : Simple image viewer with Go-GTK