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
+8.1k Golang : Check if integer is power of four example
+5.9k PageSpeed : Clear or flush cache on web server
+20.5k Golang : Secure(TLS) connection between server and client
+4.5k JavaScript : Rounding number to decimal formats to display currency
+7.2k Golang : Calculate how many weeks left to go in a given year
+6.6k Golang : Humanize and Titleize functions
+11.5k Golang : Simple file scaning and remove virus example
+11.6k Golang : GTK Input dialog box examples
+5k Golang : Customize scanner.Scanner to treat dash as part of identifier
+4.4k Java : Generate multiplication table example
+24.4k Golang : Time slice or date sort and reverse sort example
+4.9k Golang : Constant and variable names in native language