gpt4 book ai didi

c - 通过简单的函数调用将 32 位表示为 C 中的十六进制数

转载 作者:行者123 更新时间:2023-11-30 14:47:36 26 4
gpt4 key购买 nike

我想知道是否可以使用 printf 将来自微 Controller 的 32 位传入二进制数据打印为十六进制数。我已经将这些位收集到一个大整数变量中,并且我正在 printf 中尝试“%x”选项,但我似乎得到的只是 8 位值,尽管我无法判断这是否是 printf 或我的微 Controller 的限制实际上正在返回该值。

这是我从微 Controller 接收数据的代码:

 printf("Receiving...\n");
unsigned int n=0,b=0;
unsigned long lnum=0;
b=iolpt(1); //call to tell micro we want to read 32 bits
for (n=0;n<32;n++){
b=iolpt(1); //read bit one at a time
printf("Bit %d of 32 = %d\n",n,b);
lnum<<1; //shift bits in our big number left by 1 position
lnum+=b; //and add new value
}
printf("\n Data returned: %x\n",lnum); //always returns 8-bits

iolpt() 函数始终返回从微 Controller 读取的位,返回值为 0 或 1。

我对于 32 位十六进制数使用 %x 的想法是否可以接受,或者我应该尝试使用“%lx”而不是“%x”之类的东西来尝试表示长十六进制,即使它没有记录在案或者 printf 是错误的32位十六进制的函数?如果它是错误的函数,那么我可以使用一个有效的函数,还是我必须先将长数字分解为四个 8 位数字?

最佳答案

printf("Receiving...\n");

iolpt(1); // Tell micro we want to read 32 bits.
/* Is this correct? It looks pretty simple to be
initiating a read. It is the same as the calls
below, iolpt(1), so what makes it different?
Just because it is first?
*/

unsigned long lnum = 0;
for (unsigned n = 0; n < 32; n++)
{
unsigned b = iolpt(1); // Read bits one at a time.
printf("Bit %u of 32 = %u.\n", n, b);
lnum <<= 1; // Shift bits in our big number left by 1 position.
// Note this was changed to "lnum <<= 1" from "lnum << 1".
lnum += b; // And add new value.
}

printf("\n Data returned: %08lx\n", lnum);
/* Use:
0 to request leading zeros (instead of the default spaces).
8 to request a field width of 8.
l to specify long.
x to specify unsigned and hexadecimal.
*/

已修复:

  • lnum<<1;lnum <<= 1; .
  • %x决赛printf%08lx .
  • %dprintf循环到%u ,在两个地方。

此外,清理:

  • 已删除 b=初始b=iolpt(1);因为它没有被使用。
  • 移动了 b 的定义内部循环来限制其范围。
  • 移动了 n 的定义进入for限制其范围。
  • 在评论中使用正确的大写和标点符号,以提高清晰度和美观性。

关于c - 通过简单的函数调用将 32 位表示为 C 中的十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com