[英]Type casting struct to integer c++
我有一個設計要求值包含在 32 位字內的某些位。 例如,位 10-15 必須保持值 9,其余位均為 0。因此,為了簡單/可讀性,我創建了一個結構,其中包含所要求內容的分解版本。
struct {
int part1 : 10;
int part2 : 6;
int part3 : 16;
} word;
然后我可以將part2
設置為等於請求的任何值,並將其他部分設置為 0。
word.part1 = 0;
word.part2 = 9;
word.part3 = 0;
我現在想采用該結構,並將其轉換為單個 32 位整數。 我確實通過強制轉換來編譯它,但它似乎不是一種非常優雅或安全的數據轉換方式。
int x = *reinterpret_cast<int*>(&word);
如果我嘗試像普通的reinterpret_cast<int>(word)
一樣投射它,我會收到以下錯誤:
invalid cast from type 'ClassName::<anonymous struct>' to type 'int'
必須有更好的方法來做到這一點,我只是想不通。 提前致謝!
注:必須在C ++風格鑄造完成,因為標准和諸如此類的東西......眼睛卷,
union Ints {
struct {
int part1 : 10;
int part2 : 6;
int part3 : 16;
} word;
uint32_t another_way_to_access_word;
};
可能有幫助
typedef struct word {
uint32_t part1 : 10;
uint32_t part2 : 6;
uint32_t part3 : 16;
operator int() const{
return (part1 << 22) + (part2 << 16) + part3;
}
word& operator=(int i){
this->set(i);
return *this;
}
void set(int i){
part1 = (0xFFFF0000 & i) >> 16;
part2 = (0x0000FC00 & i) >> 10;
part3 = (0x000003FF & i);
}
word(int i){
this->set(i);
}
} word;
那應該這樣做。
struct word myword = 20;
struct word second_word(50);
myword = 10;
second_word.set(50);
int x = myword;
iny y = second_word;
注意:編譯和檢查。
嘗試reinterpret_cast<int>(word)
不起作用,因為在用戶定義的結構類型和int
之間沒有定義轉換運算符。
您可以將轉換運算符添加到您的結構中,或者最好是 IMHO 一個命名函數來進行轉換,例如:
struct {
uint32_t part1 : 10;
uint32_t part2 : 6;
uint32_t part3 : 16;
uint32_t get_all_parts() const
{
return (part1 << 22) + (part2 << 16) + part3;
}
} word;
請注意,我使用了無符號整數,因為它們在左移時具有明確定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.