2

Is it possible to read a command line argument as binary number? If yes, how?

E.g., ./a -v 10010110

This option allows the user to choose which register to be used out of 12 registers. I want the user to pass a 16-bits binary number with the register needed to be read with flag 1, otherwise with flat 0.

This is the idea I have in mind. If it is not a good idea, how can I accomplish it without confusing the user?

Salahuddin
  • 1,617
  • 3
  • 23
  • 37
  • 7
    command line arguments are passed to your program as strings. You'll need to convert the string "10010110" to a binary representation in the argument-parsing portion of your program. It's a fine idea, you can pass whatever you want as command line arguments. Just make it clear in the help menu/documentation what kinds of inputs your program expects and what their formats should be. – yano Mar 22 '18 at 16:24
  • 3
    An alternative is that the user passes a list of numbers, like `2 3 5 8` instead of trying to set the correct bits. I would like it a lot more to write `12` rather than `100000000000`. :-) – Bo Persson Mar 22 '18 at 16:57

1 Answers1

5

The values passed on the command line are strings. Inside the program, you may treat the strings in any manner you choose.

If you need to get a single bit from 0..15 (or 1..16) set, you'd be better off taking the decimal number of the bit than forcing the user to do the counting. You simply take argv[2] or whatever index contains the number, convert it using a function such as atoi() or strtol() into a number bitnum (error check the value for negative or large values), and then use 1U << bitnum to get the value in a 16-bit unsigned short, or equivalent.

If the user can specify several registers in one command invocation, then binary is more reasonable (though not necessarily wholly reasonable), but do consider the merits of hex over binary (one hex digit controls the value of four bits).

If you insist on using binary, then strtol() is the function to use; it will convert a string as binary (char *eos; int bitnum = strtol(argv[2], &eos, 2); — and then check the conversion carefully; you need to set errno to 0 before the conversion, and look hard at the return values and where eos points).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278