Golang : Convert an executable file into []byte example
This small utility program will read an executable file(or just any file) and convert the content into a []byte
slice. For our learning purpose, we will write a simple Hello World program using C language and convert the executable file a.out
into []byte
slice.
Here you go!
HelloWorld.c
#include <stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
and after compiling with gcc
, we will get small a.out
executable file. The Golang program below will convert the executable file to []byte
slice, which we will use for the next tutorial...which is about giving birth to another program during runtime.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file, err := ioutil.ReadFile("a.out")
if err != nil {
panic(err)
}
// get the size of file
size := len(file)
// out the file content
fmt.Print("[]byte{")
for k, v := range file {
fmt.Print(v)
if k < size-1 {
fmt.Print(",")
}
}
fmt.Print("}")
}
See also : Golang : A program that contain another program and executes it during run-time
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
+12.4k Golang : Tutorial on loading GOB and PEM files
+12.8k Golang : Google Drive API upload and rename example
+20.4k Golang : Join arrays or slices example
+5.2k Golang : Extract sub-strings
+3.9k Fix Google Analytics Redundant Hostnames problem
+20k Golang : Convert(cast) string to rune and back to string example
+32.5k Golang : Proper way to set function argument default value
+3.5k Golang : Valued expressions and functions example
+21.6k Golang : Strings to lowercase and uppercase example
+8.5k Golang : Eroding and dilating image with OpenCV example
+5.1k Golang : Process non-XML/JSON formatted ASCII text file example
+11.5k Generate salted password with OpenSSL example