是否可以将3个数字插入2个字节变量? [英] Is it possible to insert three numbers into 2 bytes variable?

查看:131
本文介绍了是否可以将3个数字插入2个字节变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我要存储包含天,月,年的日期。

For example, I want to store date which contain days, months, years.


  • 天 - > 31 ,月 - > 12 ,年 - > 99

  • days -> 31, months -> 12, years -> 99.

要在一个变量中存储 31 12 99 并将使用移位运算符< >> 来操作它。

I want to store 31, 12, 99 in one variable and will use shift operators << and >> to manipulate it.

我所做的:

short date = 0;
date = 31; // day
date << 5;
date = 12; // month
date << 7;
date = 99; // year
printf("date: %d\n", date >> 15); // print the first value

但结果是 0
我不知道想法本身是否可能。

But the result was 0. I don't know if the idea itself is possible or not.

推荐答案

是的,可以这样做。我将使用适当的 union 来屏蔽值区域:

Yes, it's possible to do so. I would use an appropriate union to mask the value regions:

union mydate_struct {
    struct {
        uint16_t day : 5;    // 0 - 31
        uint16_t month : 4;  // 0 - 12
        uint16_t year : 7;   // 0 - 127
    };
    uint16_t date_field;
};

这会给你一个年份范围从0到127.你的决定,如果这足够你的实际用例。

This leaves you with a year range from 0 to 127. Your decision, if that's sufficient for your actual use case.

这篇关于是否可以将3个数字插入2个字节变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆