c - 使用 scanf 读取 uint8_t 数据

标签 c struct scanf bit

我编写了一个简单的 C 程序来读取小时和分钟,然后将它们相加。但它没有被添加,currentHrMin 只打印分钟的值。但是,如果在打印 currentHrMin 之后调用 getCurrentDate(&dateParams),则没有问题。我无法找出我的代码有什么问题。可能是一个愚蠢的问题。我正在使用 MinGW C 编译器。

#include <stdio.h>
#include <stdint.h>

#define BCD_TO_DEC(num) ((((num)&0xF0)>>4)*10+((num)&0x0F))
#define DEC_TO_BCD(num) ((((num)/10) << 4) | ((num) % 10))


struct RTC_TIME
{
    uint8_t hours;
    uint8_t minutes;
    uint8_t seconds;
    uint8_t twelveHourFormat:1; //1 = 12 hour format, 0=24 hour format.
    uint8_t AM_0_PM_1:1;
    uint8_t hours24Format;
    uint8_t alarm1State:1;
    uint8_t alarm2State:1;
};

struct RTC_DATE
{
    uint8_t date;
    uint8_t month;
    uint8_t dayOfWeek;
    uint8_t year;
};


void getCurrentTime(struct RTC_TIME* time)
{
    printf("Enter Hour: ");
    scanf("%d",&(time->hours));
    printf("Enter Min: ");
    scanf("%d",&(time->minutes));
}

void getCurrentDate(struct RTC_DATE* date)
{
    printf("Enter Month: ");
    scanf("%d",&(date->month));
}

int ar1[5]= {0x1253,0x1034,0x0804,0x1112,0x0409};

int main(void)
{
    struct RTC_DATE dateParams;
    struct RTC_TIME timeParams;

    getCurrentTime(&timeParams);
    getCurrentDate(&dateParams);
    uint16_t currentHrMin = timeParams.hours*60 + timeParams.minutes;
    printf("Current hour minute = %d\n",currentHrMin);

    return(0);

}

最佳答案

包括#include <inttypes.h>之后, 变化:

scanf("%d",&(time->hours));

为此:

scanf("%" SCNu8, &(time->hours));

在你所有的 scanf 中,这样你就可以读取 uint8_t,而不是 int。


您所做的观察与此有关,您正在阅读 %d指定给类型 int 的说明符,通常是 32位。因此,当您将读取值分配给 time->hours 时,那么它也会“溢出”到相邻的结构字段。


下次,请启用你的编译器的警告,你应该得到这样的东西:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:32:16: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
    scanf("%d",&(time->hours));
           ~~  ^~~~~~~~~~~~~~
           %s
main.c:34:16: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
    scanf("%d",&(time->minutes));
           ~~  ^~~~~~~~~~~~~~~~
           %s
main.c:40:16: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
    scanf("%d",&(date->month));
           ~~  ^~~~~~~~~~~~~~
           %s
3 warnings generated.

我使用了 Wall 编译器标志,正如我在 answer 中讨论的那样.

关于c - 使用 scanf 读取 uint8_t 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44030426/

相关文章:

c - fscanf 扫描不正确的信息

c - 在头函数声明中传递常量

c - 尝试从二进制文件读取足够字节时出现问题

c - C 中的压栈、出栈操作

pointers - Golang 中 []*Users 和 *[]Users 的区别?

C++ 堆栈实现

c - 数组指针与普通指针的区别

c - 防止不断检查错误的模式?

c - 为什么在 Ubuntu 14.10 中需要按 CTRL+D 两次才能突破 `while ((c=getchar())!=EOF)`?

c - 当用户在 scanf() 中输入错误的数据类型时如何修复无限循环?