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
+6.5k Android Studio : Hello World example
+16.1k CodeIgniter/PHP : Create directory if does not exist example
+5.7k Golang : Function as an argument type example
+15.7k Golang : How to reverse elements order in map ?
+6.9k Golang : Check if one string(rune) is permutation of another string(rune)
+6.8k Golang : Validate credit card example
+18.8k Golang : Get host name or domain name from IP address
+5.8k Golang : Experimenting with the Rejang script
+10.2k Golang : Select region of interest with mouse click and crop from image
+14.3k Golang : How to get URL port?
+13.4k Golang : How to determine if a year is leap year?
+9.2k Golang : Qt Yes No and Quit message box example