作者blueblueChen (藍藍欠)
看板C_and_CPP
標題[問題] 宣告一個最小的 struct
時間Sun Aug 19 15:59:19 2018
最近去面試
有一題是考用最小的 struct去存 年月日分秒 ,假設2015,可以用 15來表示
我當時寫不出來。回來練習的時候,我是這樣宣告
struct Date {
unsigned short year : 10 //假設最大 999,需要10個bit
unsigned short month : 4 //最大12,只要4個bit
unisgned short : 2 //pendding 2 個 bit
unsigned short day : 5 //最大31,需要5個bit
unsigned short hour : 5 //最大23,需要5個bit
unsigned short minute : 6 //最大60,需要6個bit
unsigned char second //不管是 char 還是 short 都會再多兩個 byte
} date
sizeof(date) = 6 byte
這是我的答案,請問還有沒有更小的 struct 呢?
感謝指教,多謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.68.215.61
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1534665561.A.5F6.html
1F:推 AstralBrain: time_t (完 08/19 16:43
2F:推 jerryh001: time_t正解 08/19 17:21
3F:推 chuegou: 同上面兩位 08/19 23:39
4F:→ Killercat: 挑個小毛病 不過time_t不是struct XD 08/20 07:35
5F:→ Killercat: 要拿個struct把time_t包起來這樣 :P 08/20 07:35
6F:→ lantw44: 可是 64-bit 的 time_t 是 8 bytes 似乎沒有比較小? 08/20 23:53
7F:推 AstralBrain: 嗯.. 算了一下 原po只要存一千年的話5byte夠用了 XD 08/21 01:41
8F:→ AstralBrain: 要拿來計算的時候前面補零就好 08/21 01:41
9F:推 xvid: 沒提範圍那用個32位元無號整數就好 08/21 10:04
10F:推 LPH66: 回應樓上的 5 byte, FAT 檔案格式的時間戳總共也是 5 byte 08/21 19:01
11F:→ LPH66: 它的範圍是 128 年, 精確到百分之一秒 08/21 19:01
12F:→ LPH66: 而且也是使用和原 PO 想法差不多的 bitfield 儲存 08/21 19:02
13F:→ LPH66: 所以若精確度到秒, 一千年範圍用 5 byte 是確定夠用的 08/21 19:02
14F:推 LPH66: 話說回來, 原 PO 的秒數應該不會用到 2 byte 08/21 19:05
15F:→ LPH66: 除非是結構對齊要求, 所以理論上這就是 5 byte 的答案了 08/21 19:06
16F:→ blueblueChen: L大,因為它會自動對齊,秒數那邊不管是char還是 08/25 09:22
17F:→ blueblueChen: 用 short 的 bitfield 都會占用2 byte 08/25 09:22