gpt4 book ai didi

c - 如何将三个无符号整数打包成 C 中的一个无符号短整数

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:20 25 4
gpt4 key购买 nike

我有一个大学作业,其中我必须使用 C 打包三个代表日期的无符号整数(年份必须在 1970 到 2097 之间)并将其压缩成一个无符号短整数,然后再次解压并在命令行中显示。

有人可以帮帮我吗?

下面我留下我目前的代码(函数外声明的变量和函数签名不能更改)

编辑:我有第二个问题,即 getchar 函数不返回任何内容,将三个日期字段设置为 0...

#include <stdio.h>

typedef unsigned short pkdate_t;
typedef struct date3 {
unsigned year;
unsigned month;
unsigned day;
} date3_t;

int ror (int val, unsigned n) {
return (val >> n)|(n << (32 - n));
}

int pack_date (pkdate_t * dst, date3_t * src) {
if ((*src).year < 1097 || (*src).year > 2097 || (*src).month < 1 || (*src).month > 12 || (*src).day < 1 ||
((*src).month == 2 && (((*src).year / 4 == 0 && (*src).day > 29) || ((*src).year / 4 != 0 && (*src).day > 28))) ||
(((*src).month == 2 || (*src).month == 4 || (*src).month == 6 || (*src).month == 9 || (*src).month == 11) && (*src).day == 31)) return -1;

//(*dst) = (*src).year * 10 + (*src).month + (*src).day; "wrong code"

return 0;
}

int unpack_date (date3_t * dst, pkdate_t date) {
(*dst).year = date % 10000;
date = date / 10000;
(*dst).month = date % 100;
date = date / 100;
(*dst).day = date % 100;

if ((*dst).year < 1097 || (*dst).year > 2097 || (*dst).month < 1 || (*dst).month > 12 || (*dst).day < 1 ||
((*dst).month == 2 && (((*dst).year / 4 == 0 && (*dst).day > 29) || ((*dst).year / 4 != 0 && (*dst).day > 28))) ||
(((*dst).month == 2 || (*dst).month == 4 || (*dst).month == 6 || (*dst).month == 9 || (*dst).month == 11) && (*dst).day == 31)) return -1;
else return 0;
}

int main () {
int k = ror(30, 2);
printf("%s\n", "exercicio 1:");
printf("%d turned into %d\n", 30, k);

pkdate_t date = 0;
date3_t newDate;
newDate.year = 2000;
newDate.month = 04;
newDate.day = 02;
printf("%s\n", "exercicio 2:");
//printf("%s\n", "insira uma data (yyyymmdd) e de seguida pressione enter:");

//int i = 1000;

//while (i > 0) {
//newDate.year += getchar() * i;
//i = i / 10;
//}

//i = 10;

//while (i > 0) {
//newDate.month += getchar() * i;
//i = i / 10;
//}

//i = 10;

//while (i > 0) {
//newDate.day += getchar() * i;
//i = i / 10;
//}

//"the commented part above does not get any values from command line, still figuring that part out :)"

pack_date(&date, &newDate);

printf("packed date: %hu\n", date);

unpack_date(&newDate, date);

printf("unpacked date: %u/%u/%u\n", newDate.year, newDate.month, newDate.day);

//newDate.year = 2000;
//newDate.month = 12;
//newDate.day = 14;
//pack_date(&date, &newDate);
//printf("%s\n", "exercicio 3:");
//printf("date is %hu\n", date);

// "ignore"

return 0;
}

最佳答案

在 C 语言中,没有那么多符合位域条件的用例,但是恕我直言,这个非常适合,因为它可以让您免去很多位移位带来的麻烦:

struct date_struct
{
unsigned short year:7;
unsigned short month:4;
unsigned short day:5;
};

union date
{
struct date_struct bits;
short date;
}

关于c - 如何将三个无符号整数打包成 C 中的一个无符号短整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428441/

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