[英]Can I read command line argument as binary?
Is it possible to read a command line argument as binary number? 是否可以将命令行参数读取为二进制数? If yes, how? 如果是,怎么办?
Eg, ./a -v 10010110
例如,。/ ./a -v 10010110
This option allows the user to choose which register to be used out of 12 registers. 该选项允许用户从12个寄存器中选择要使用的寄存器。 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
. 我希望用户传递一个16位二进制数,该标志需要使用标志1
来读取需要的寄存器,否则使用平面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? 如果不是一个好主意,如何在不引起用户混淆的情况下完成它?
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. 如果您需要从0..15(或1..16)中设置一位,那么最好不要使用该位的十进制数字,而要强迫用户进行计数。 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. 您只需使用argv[2]
或任何包含数字的索引,然后使用atoi()
或strtol()
类的函数将其转换为数字bitnum
(错误检查值是否为负或大值),然后使用1U << bitnum
以16位unsigned short
或等效形式获取值。
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; 如果坚持使用二进制,则strtol()
是要使用的函数; 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). 它将字符串转换为二进制( char *eos; int bitnum = strtol(argv[2], &eos, 2);
—然后仔细检查转换 ;您需要在转换前将errno
为0,然后仔细看一下返回值以及eos
指向的位置)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.