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
+4.2k Golang : Join lines with certain suffix symbol example
+7.8k Golang : Use regular expression to get all upper case or lower case characters example
+12.1k Golang : Get all local users and print out their home directory, description and group id
+6.2k Golang : Get final or effective URL with Request.URL example
+17.6k Golang : How to Set or Add Header http.ResponseWriter?
+4k Unix/Linux/MacOSx : Get local IP address
+6k Gogland : Single File versus Go Application Run Configurations
+4.9k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+4.1k Cash Flow : 50 days to pay your credit card debt
+7.8k Golang : Check if user agent is a robot or crawler example
+18.1k Golang : Create and resolve(read) symbolic links
+4k Swift : Convert string array to array example