This is my first golang program. It accepts an integer and prints the corresponding decimal, octal, hex and binary values. It also prints the %v and %#v.
This seems to work for all except binary numbers.
Here is the program:
package main
import "fmt"
func main() {
var numberInput int
fmt.Printf("Enter the number: ")
fmt.Scanf("%v", &numberInput)
fmt.Printf("Dec %d\n", numberInput)
fmt.Printf("Hex %#x\n", numberInput)
fmt.Printf("Oct %#o\n", numberInput)
fmt.Printf("Bin %b\n", numberInput)
fmt.Printf("Value Format %v\n", numberInput)
fmt.Printf("Go Value Format %#v\n", numberInput)
}
And here is the output:
C:\Users\pmu\go\src>first.exe
Enter the number: 100
Dec 100
Hex 0x64
Oct 0144
Bin 1100100
Value Format 100
Go Value Format 100
C:\Users\pmu\go\src>first.exe
Enter the number: 0xFFFF
Dec 65535
Hex 0xffff
Oct 0177777
Bin 1111111111111111
Value Format 65535
Go Value Format 65535
C:\Users\pmu\go\src>first.exe
Enter the number: 07777
Dec 4095
Hex 0xfff
Oct 07777
Bin 111111111111
Value Format 4095
Go Value Format 4095
But when I enter a binary number, it does not work. Note I tried adding “b” at the beginning of the number because, if I dont, then there are two things that will happen:
Suppose I enter “1010” then it will be thought as decimal 1010
Suppose I enter “011011” then it will be thought as octal, because octals have a 0 attached at the beginning.
C:\Users\pmu\go\src>first.exe
Enter the number: b1010
Dec 0
Hex 0x0
Oct 0
Bin 0
Value Format 0
Go Value Format 0
C:\Users\pmu\go\src>first.exe
Enter the number: bx1010
Dec 0
Hex 0x0
Oct 0
Bin 0
Value Format 0
Go Value Format 0
C:\Users\pmu\go\src>first.exe
Enter the number: 1010b
Dec 1010
Hex 0x3f2
Oct 01762
Bin 1111110010
Value Format 1010
Go Value Format 1010
C:\Users\pmu\go\src>
I know this is not the right way to make the program understand that I want to enter a binary value, but then, how do I do it?
Any help will be appreciated.
fmt.Scanf("%v") will only parse valid integer literals, and as you can see in the languages spec about integer literals, there is simply no way to express a binary integer.
strconv.ParseInt() accepts the numeric base you want as an argument, so you could check for whatever prefix you want to use to indicate binary, then convert from base 2. Converting hexidecimal, octal, and decimal numbers is easy. Just specify a base of 0.
I think you are posting too late at night or one is too many. Also, I wasn’t careful enough with my writing. (I’ve not been at 100% for writing for the past few days.) Sorry about that!
When you give a “base” of 0 to ParseInt(), it is a special case. Then it can decode hex, octal, or decimal numbers, depending on the prefix: 0x for hex, 0 for octal, and none for decimal. (In other words, just like in C/C++/Go and other popular programming languages.