Last active
January 1, 2025 04:42
-
-
Save azlan/2abc2322e5a604d8f32cd60a523bfa76 to your computer and use it in GitHub Desktop.
decimal to hex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"encoding/binary" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
"github.com/mattn/go-isatty" | |
) | |
func main() { | |
args := os.Args | |
writeAsBinary := false | |
if len(args) == 2 { | |
if args[1] == "bin" { | |
writeAsBinary = true | |
} | |
} | |
isattyIn := isatty.IsTerminal(os.Stdin.Fd()) | |
isattyOut := isatty.IsTerminal(os.Stdout.Fd()) | |
if isattyIn { | |
fmt.Print("Enter text: ") | |
} | |
input := make([]byte, 0, 1024) | |
scanner := bufio.NewScanner(os.Stdin) | |
scanner.Split(bufio.ScanWords) | |
for scanner.Scan() { | |
str := scanner.Text() | |
if len(str) == 0 { | |
continue | |
} | |
i, err := strconv.Atoi(str) | |
check(err) | |
if i >= 256 { | |
log.Fatalln("value is bigger than 1 byte:", i) | |
} else { | |
input = append(input, byte(i)) | |
} | |
} | |
if err := scanner.Err(); err != nil { | |
fmt.Fprintln(os.Stderr, "reading standard input:", err) | |
} | |
// if output is piped to with bin flag | |
if !isattyOut && writeAsBinary { | |
err := binary.Write(os.Stdout, binary.LittleEndian, input) | |
check(err) | |
if err != nil { | |
os.Exit(1) | |
} else { | |
os.Exit(0) | |
} | |
} | |
var b strings.Builder | |
for i, v := range input { | |
_, err := b.WriteString(fmt.Sprintf("%02X ", v)) | |
check(err) | |
if (i+1)%16 == 0 { | |
fmt.Println(b.String()) | |
b.Reset() | |
} | |
} | |
fmt.Println(b.String()) | |
} | |
func check(e error) { | |
if e != nil { | |
log.Fatalln(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment