[問題] int 4 bits

看板C_and_CPP作者 (哈味)時間8年前 (2016/06/22 10:13), 8年前編輯推噓7(7015)
留言22則, 7人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC 問題(Question): 想要宣告一個4bits的正整數, 存放範圍 0~15 不曉得這樣的宣告方式正不正確? struct { unsigned int boy : 4; unsigned int girl : 4; } age; 不曉得這樣是不是 boy 4 bits girl 4 bits 我看網路資料他的參考Example是 struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status; The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to store the values. 宣告4 bytes 但是只有2 bits會存放到memory 感謝大大幫忙! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.117.89.77 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1466561627.A.057.html ※ 編輯: hardware (140.117.89.77), 06/22/2016 10:17:56

06/22 10:25, , 1F
06/22 10:25, 1F

06/22 10:26, , 2F
每次看這種code,都有一種 "真的有必要那麼省嗎?"
06/22 10:26, 2F

06/22 10:28, , 3F
不是4 bytes都會被allocate,但只有使用到2 bits嗎?
06/22 10:28, 3F

06/22 10:28, , 4F
所以記憶體中佔的空間還是4 bytes
06/22 10:28, 4F

06/22 10:31, , 5F
Just do it
06/22 10:31, 5F

06/22 10:33, , 6F
補充一下,我回的是 "不曉得這樣的宣告方式正不正確?"
06/22 10:33, 6F

06/22 10:44, , 7F
沒錯有必要那麼省嗎 除非為了送給哪個硬體
06/22 10:44, 7F

06/22 12:30, , 8F
bit field 不是 implementation defined 嗎?
06/22 12:30, 8F

06/22 12:30, , 9F
這應該 non portable 吧
06/22 12:30, 9F

06/22 12:41, , 10F
to s25g5d4,是的
06/22 12:41, 10F

06/22 12:42, , 11F
實際大小會隨著compiler與machine而不同
06/22 12:42, 11F

06/22 12:43, , 12F
上次就有人問過了#1NFTpMBr
06/22 12:43, 12F

06/22 14:57, , 13F
不是省不省的問題 有些封包表頭只能這樣
06/22 14:57, 13F

06/22 14:57, , 14F
宣告
06/22 14:57, 14F

06/22 15:02, , 15F
這個看起來不是那個用途。
06/22 15:02, 15F

06/22 16:37, , 16F
封包表頭誰叫你這樣宣告的 請正常宣告 uint8_t 再 shift
06/22 16:37, 16F

06/22 16:37, , 17F
好嗎 = =
06/22 16:37, 17F

06/22 19:24, , 18F
通常這種structure都是對應硬體register
06/22 19:24, 18F

06/22 20:41, , 19F
推樓上 韌體上處理些資料好用喔
06/22 20:41, 19F

06/23 11:00, , 20F
linux給的表頭都是這樣啊 錯了嗎QQ
06/23 11:00, 20F

06/23 11:01, , 21F
而且bit shift太麻煩了吧 結構指標能完成的幹嘛還要自己b
06/23 11:01, 21F

06/23 11:01, , 22F
it shift
06/23 11:01, 22F
文章代碼(AID): #1NQVHR1N (C_and_CPP)