From: Colin Patrick Mccabe Date: Fri, 28 Sep 2012 23:45:44 +0000 (-0700) Subject: Add bytor.go X-Git-Url: http://club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a3ff5a41a6d295706e98b3f395286be7d8c39458;p=cmccabe-bin Add bytor.go Add bytor.go to convert between Java-style signed int bytes to normal hex bytes. For example a byte with value -1 in Java-speak has value 0xff in hex. Signed-off-by: Colin McCabe --- diff --git a/.gitignore b/.gitignore index 85ab56e..65c02f9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ # # binaries +bytor errno_speak simple_time vimstart diff --git a/Makefile b/Makefile index e8baa16..20180f3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,9 @@ CFLAGS=-Wall -O2 -all: errno_speak show_default_sockopts simple_time vimstart +all: bytor errno_speak show_default_sockopts simple_time vimstart + +bytor: + go build bytor.go errno_speak: errno_speak.o diff --git a/bytor.go b/bytor.go new file mode 100644 index 0000000..c5f5689 --- /dev/null +++ b/bytor.go @@ -0,0 +1,46 @@ +package main + +import "fmt" +import "os" +import "strconv" + +func usage(retval int) { + fmt.Printf("bytor: converts bytes between hex and decimal.\n" + + "\n" + + "usage: bytor [flags] [number-to-convert]\n" + + "\n" + + "Numbers with the prefix '0x' will be interpreted as \n" + + "hexadecimal; others will be interpreted as decimal.\n" + + "\n" + + "Flags:\n" + + "-d: Decimal output (default is hex.)\n" + + "-h/--help: This help message\n") + os.Exit(retval) +} + +func main() { + formatStr := "0x%02x\n" + i := 1 + if (len(os.Args) < 2) { + usage(1) + } + if ((os.Args[i] == "-h") || (os.Args[i] == "--help")) { + usage(0) + } + if (os.Args[i] == "-d") { + formatStr = "%d\n" + i++ + } + if (i >= len(os.Args)) { + usage(1) + } + val, err := strconv.ParseInt(os.Args[i], 0, 8) + if (err != nil) { + fmt.Printf("Error parsing input: %v\n", err) + os.Exit(1) + } + if (val < 0) { + val = 0x100 + val; + } + fmt.Printf(formatStr, val) +}