如何在 WINAVR 中组合两个接收到的输入并将其作为一个整数读取?

发布于 2024-09-30 06:01:34 字数 434 浏览 9 评论 0原文

我希望用户使用 c=ReceiveByte() 命令输入 2 位数字。例如,我希望用户执行以下操作:

Enter 5
Enter 3
Output number 53 in ascii value on screen ( using hyperterminal )
Store number in a single array
Use that number for other loops etc.

我的草稿代码是:

.
.
int c1[3];
c1[0]=ReceiveByte();
c1[1]=ReceiveByte();
.
.
for(i=0;i<3;i++)
 TransmitByte(c1[i]);
.
.

这是正确的吗?或者我是否错误地存储了这两位数字?

非常感谢您的帮助!

I want users to enter 2 digits using c=ReceiveByte() command. For example, I want the user to do the following :

Enter 5
Enter 3
Output number 53 in ascii value on screen ( using hyperterminal )
Store number in a single array
Use that number for other loops etc.

My draft code is :

.
.
int c1[3];
c1[0]=ReceiveByte();
c1[1]=ReceiveByte();
.
.
for(i=0;i<3;i++)
 TransmitByte(c1[i]);
.
.

Is this right ? or am I storing the 2 digits incorrectly ?

Thanks alot for your help !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小帐篷 2024-10-07 06:01:34

对于输出,您不需要修改 c1[0] 和 c1[1],因为它们已经包含输入的字符。 您只需要确保 c1[2] 包含有效字符,例如顺便说一句:

c1[2] = '\n';

按照您的代码,如果您需要将输入的数字作为 int 获取,

int num = (c1[0] - '0') * 10 + (c1[1] - '0');

For output, you don't need to modify c1[0] and c1[1] since these already contain the characters as entered. As your code stands you just need to make sure that c1[2] contains a valid character, e.g.

c1[2] = '\n';

BTW, if you need to get the entered number as an int:

int num = (c1[0] - '0') * 10 + (c1[1] - '0');
錯遇了你 2024-10-07 06:01:34

由于您似乎从 Receivebyte() 函数接收字节,因此您应该将它们存储为字节(无符号字符),而不是整数,因为使用整数存储单个字节会浪费 3 个字节的内存。

否则,您的 echo 实现应该可以工作 - 即使您可能想要添加防护措施以防止用户发送非数字字符。

您必须将 ASCII 字符“5”和“3”(ASCII 代码 53 和 51)转换为它们的数值(每个减去 48,因为 ASCII 编码方案中数字范围为 48 到 57)

Since you seem to be receiving bytes from the Receivebyte() function, you ought to store them as bytes (unsigned char), not as integers, since using an integer to store a single byte wastes it's 3 bytes of memory.

Otherwise, your echo implementation should work - even though you might want to add guards against a user sending characters wich are non-numeric.

You will have to convert the ASCII Characters '5' and '3' (ASCII codes 53 and 51) to theire numeric value (subtract 48 from each as numbers range from 48 to 57 in the ASCII coding scheme)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文