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 :

http://www.cnblogs.com/golove/p/3282667.html





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