使用scanf读取uint8_t数据

时间:2017-05-17 16:35:18

标签: c struct scanf bit

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

}

1 个答案:

答案 0 :(得分:8)

包括#include <inttypes.h>后,请更改:

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

到此:

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

在你所有的scanf中,以便你读取uint8_t而不是int。

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

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

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中所讨论的那样。