英文:
C++ (Arduino) BIN is working, but where is it documented? What is this thing called?
问题
randBinary = random(BIN);
这行代码已被翻译为中文。
英文:
I coded this (BIN) into my Arduino sketch, and it's working (binary as expected), but I don't see it documented anywhere, so I don't know how to use it better, find others like it, and use it elsewhere. I guess I'd like to know the correct "programmer-speak", so I can do more research into other available options in similar scenarios:
randBinary = random(BIN);
I hacked the above into my code after seeing the following on official documentation (use of BIN):
Serial.print(78, BIN) gives "1001110"
from: https://www.arduino.cc/reference/en/language/functions/communication/serial/print/
答案1
得分: 1
BIN是一个预处理宏,定义为#define BIN 2
。它在Print.h中定义,用作print
函数的第二个参数,其中第一个参数是整数数值类型。第二个参数指定要打印数字的进制。默认为十进制(DEC)。计算机中使用的其他常见进制格式包括二进制、十六进制和八进制,因此Print.h中有预处理宏分别为10、2、16和8,分别称为DEC、BIN、HEX和OCT。可以使用数字作为第二个参数使用print
函数来使用其他进制格式。(注意:对于print
函数的第一个参数为浮点数或双精度浮点数的情况,第二个参数是要打印的小数位数。)
Arduino中的random函数有两个重载版本。一个版本有一个参数max
,另一个版本有两个参数min
和max
。
random的参数指定所需的范围。例如,如果您想选择一周中的随机一天,您将使用random(7)
或random (1, 8)
。另一个例子是,如果您想模拟掷骰子,您将使用random(1, 7)
。
不应该将BIN用作random
的参数。它会起作用,因为BIN是2,但这不是宏BIN的预期用途。
英文:
BIN is a preprocessor macro defined as #define BIN 2
. It is defined in Print.h to use as second parameter of print
functions where the first parameter is of integer numeric type. The second parameter specifies the base in which the number should be printed. Default is decimal (DEC) of course. Other common number base formats used in computers are binary, hexadecimal and octal, so Print.h has preprocessor macros for 10, 2, 16 and 8 called DEC, BIN, HEX and OCT. The print function can be used with other base formats using a number as the second parameter. (Note. The second parameter in print function with first parameter as float or double is count of decimal places to print.)
The function random in Arduino has 2 overloaded versions. A version with one parameter max
and a version with two parameters min' and
max'.
The parameters of random specify the required range. For example if you want to choose a random day of week you will use random(7)
or random (1, 8)
. Other example is if you want to simulate a dice roll you will use random(1, 7)
.
You should not use BIN as parameter forrandom
. It will work because BIN is 2, but it is not the intended use of the macro BIN.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论