Unable to save a float value to a bitfield structure

后端 未结 5 1806
时光说笑
时光说笑 2020-12-18 11:16

I have a structure

struct {
   u32 var1 :7;
   u32 var2 :4;
   u32 var3 :4;
   u32 var4 :1;
   u32 var5 :4;
   u32 var6 :7;
   u32 var7 :4;
   u32 var8 :1;
          


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 11:55

    You can't store a double (64 bits) into a field of only 4 bits. You can either do it this way:

    struct {
       u32 var1 :7;
       u32 var2 :4;
       u32 var3 :4;
       u32 var4 :1;
       double var5;
       u32 var6 :7;
       u32 var7 :4;
       u32 var8 :1;
            } my_struct; 
    

    or this way

    struct {
       u32 var1 :7;
       u32 var2 :4;
       u32 var3 :4;
       u32 var4 :1;
       u64 var5 :64;
       u32 var6 :7;
       u32 var7 :4;
       u32 var8 :1;
            } my_struct; 
      ..
    
      struct1[i].var5 = *(u64*)&x; // reinterpret the double as a memory array of 8 bytes
    

    The second way is not recommended.

    If you want to store 64 bits in 4 bits, read up on how floating point (IEEE) works. http://en.wikipedia.org/wiki/IEEE_floating_point

提交回复
热议问题