簡體   English   中英

如何將uint8轉換為表示字節的結構?

[英]How I can cast an uint8 to a struct representing a byte?

我有一個結構,表示一個具有固定偏移量0b1111的字節。 我定義了一個轉換操作符,將SByte轉換為unit8。

  1. 如何進行相反的轉換(從uint8到SByte)?
  2. 是替換在首位uint8_t或者一個聯盟為SByte唯一的解決辦法?
struct SByte
{
  uint8_t offset : 4;
  uint8_t bit4 : 1;
  uint8_t bit5 : 1;
  uint8_t bit6 : 1;
  uint8_t bit7 : 1;

  SByte():offset(15), bit4(0), bit5(0), bit6(0), bit7(0){}
  explicit operator int8_t() const
  {
    return static_cast<uint8_t>((bit7 << 7) | (bit6 << 6) | (bit5 << 5) | (bit4 << 4));
  }
};
int main()
{
  auto lbyte = SByte();
  auto result = static_cast<int8_t>(lbyte);
  assert(result == 15); // 0b00001111
}

如何進行相反的轉換(從uint8到SByte)?

通過定義一個構造函數:

explicit SByte(uint8_t byte) {
    // extract individual bits from `byte`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM