<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865689</guid>
        <pubDate>Sun, 15 May 2022 13:02:41 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865689</link>
        <description><![CDATA[Majestio: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=427269&view=findpost&p=3865687'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>Majestio &#064; <time class="tag-quote__quoted-time" datetime="2022-05-15T15:22:48+03:00">15.05.22, 12:22</time></span><div class='quote '>Думаю, имеет смысл погуглить про особенности именно MSVC 2017.</div></div><br>
Ну в догонку ... Мелкомягкие имеют <a class='tag-url' href='https://docs.microsoft.com/en-us/cpp/cpp/cpp-bit-fields?redirectedfrom=MSDN&view=msvc-170' target='_blank'>свою точку зрения</a> на упаковку битовых полей.]]></description>
        <author>Majestio</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865688</guid>
        <pubDate>Sun, 15 May 2022 12:36:18 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865688</link>
        <description><![CDATA[DrUnkard: Я тут другое поискал. Нашел ручную кодировку / раскодировку SBUS. Буду применять ее и не заморачиваться своими хитростями. :yes-sad: <br>
Кому интересно - тут Функции:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">bool SBUS::read(uint16_t* channels, bool* failsafe, bool* lostFrame)</div><div class="code_line">&nbsp;</div><div class="code_line">void SBUS::write(uint16_t* channels)</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script><br>
<a class='tag-url' href='https://github.com/TheDIYGuy999/SBUS/blob/master/src/SBUS.cpp' target='_blank'>https://github.com/TheDIYGuy999/SBUS/blob/m...er/src/SBUS.cpp</a><br>
<br>
Спасибо всем добрым людям.  :D]]></description>
        <author>DrUnkard</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865687</guid>
        <pubDate>Sun, 15 May 2022 12:22:48 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865687</link>
        <description><![CDATA[Majestio: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=427269&view=findpost&p=3865685'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>DrUnkard &#064; <time class="tag-quote__quoted-time" datetime="2022-05-15T11:36:07+00:00">15.05.22, 11:36</time></span><div class='quote '>Видимо придётся отказаться от хитрого плана и перекодировать всё вручную.</div></div><br>
Думаю, имеет смысл погуглить про особенности именно MSVC 2017.]]></description>
        <author>Majestio</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865685</guid>
        <pubDate>Sun, 15 May 2022 11:36:07 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865685</link>
        <description><![CDATA[DrUnkard: <strong class='tag-b'>Majestio</strong>, спасибо.<br>
У меня стандарт Си++ 17<br>
Сходил по твоей ссылке. Там вижу реально размер структуры 25 байт.<br>
Скопировал твой код себе. Запустил - всё равно 35 байтов.  &gt;:( <br>
Использую MSVC 2017.<br>
<br>
Видимо придётся отказаться от хитрого плана и перекодировать всё вручную.  &lt;_&lt;]]></description>
        <author>DrUnkard</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865666</guid>
        <pubDate>Sun, 15 May 2022 05:34:30 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865666</link>
        <description><![CDATA[Majestio: С битовыми полями не все так просто. По стандарту там многое зависит от реализации. Вот кусочек стандарта &quot;Стандарт-Си++ 2017 (ISO-IEC_14882-2017)&quot; (обрати внимание на выделенное красным):<br>
<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '><strong class='tag-b'><br>
12.2.4 Bit-fields</strong><br>
<br>
1. A member-declarator of the form<br>
<br>
<span class="tag-color tag-color-named" data-value="blue" style="color: blue"><pre>identifieropt attribute-specifier-seqopt : constant-expression brace-or-equal-initializeropt</pre></span><br>
specifies a bit-field; its length is set off from the bit-field name by a colon. The optional attribute-specifier-seq appertains to the entity being declared. The bit-field attribute is not part of the type of the class member. The constant-expression shall be an integral constant expression with a value greater than or equal to zero. The value of the integral constant expression may be larger than the number of bits in the object representation (6.9) of the bit-field’s type; in such cases the extra bits are padding bits (6.9). <span class="tag-color tag-color-named" data-value="red" style="color: red"><strong class='tag-b'>Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined</strong></span>. Bit-fields are packed into some addressable allocation unit. <br>
[ Note: Bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others. —end note ]<br>
<br>
2. A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [ Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. —end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.<br>
<br>
3. A bit-field shall not be a static member. A bit-field shall have integral or enumeration type (6.9.1). A bool value can successfully be stored in a bit-field of any nonzero size. The address-of operator &amp; shall not be applied to a bit-field, so there are no pointers to bit-fields. A non-const reference shall not be bound to a bit-field (11.6.3). [ Note: If the initializer for a reference of type const T&amp; is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly. See 11.6.3. —end note ]<br>
<br>
4. If the value true or false is stored into a bit-field of type bool of any size (including a one bit bit-field), the original bool value and the value of the bit-field shall compare equal. If the value of an enumerator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type (10.2), the original enumerator value and the value of the bit-field shall compare equal.<br>
</div></div><br>
<br>
А вот кусочек из &quot;Стандарт-Си-2018 (ISO-IEC_ 9899-2018)&quot;:<br>
<br>
<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '><br>
<strong class='tag-b'>6.7.2.1 Structure and union specifiers</strong><br>
...<br>
11.An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. <span class="tag-color tag-color-named" data-value="red" style="color: red"><strong class='tag-b'>If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined.</strong></span> The alignment of the addressable storage unit is unspecified.<br>
...<br>
</div></div><br>
<br>
Я попробовал в онлайн-компиляторе твой код, предварительно изменив твои типы на типы из стандартной библиотеки - там все как ты хотел:<br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;cstdio&#62;</div><div class="code_line">#include &#60;cstdint&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">#pragma pack(push, 1) //</div><div class="code_line">typedef struct tag_sbus_dat {</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint8_t &nbsp;StartByte;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch0 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch1 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch2 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch3 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch4 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch5 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch6 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch7 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch8 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch9 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch10 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch11 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch12 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch13 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch14 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint16_t ch15 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint8_t &nbsp;FlagsByte;</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint8_t &nbsp;EndByte;</div><div class="code_line">} &nbsp;SBUS_DAT;</div><div class="code_line">#pragma pack(pop)</div><div class="code_line">&nbsp;</div><div class="code_line">typedef union</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp;uint8_t byte[25];</div><div class="code_line">&nbsp;&nbsp; &nbsp;SBUS_DAT msg;</div><div class="code_line">} Sbus_msg;</div><div class="code_line">&nbsp;</div><div class="code_line">int main()</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp;Sbus_msg Sbus_Data;</div><div class="code_line">&nbsp;&nbsp; &nbsp;printf(&quot;sizeof data is %ld\n&quot;, sizeof(Sbus_Data));</div><div class="code_line">&nbsp;&nbsp; &nbsp;return 0;</div><div class="code_line">}</div></ol></div></div></div></div><br>
<br>
<a class='tag-url' href='https://onlinegdb.com/Cyn-Rqok-' target='_blank'>https://onlinegdb.com/Cyn-Rqok-</a>]]></description>
        <author>Majestio</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865665</guid>
        <pubDate>Sat, 14 May 2022 23:07:40 +0000</pubDate>
        <title>Битовые поля структуры не хотят паковаться</title>
        <link>https://forum.sources.ru/index.php?showtopic=427269&amp;view=findpost&amp;p=3865665</link>
        <description><![CDATA[DrUnkard: Решил хитро преобразовывать данные протокола SBUS в байты и обратно. Через объявление структуры и объединение. Но что-то пошло не так... :D <br>
Значения в одном канале для SBUS есть 11-битное число. Отправка же всех данных по USART идёт побайтно. <br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#pragma pack(push, 1) //</div><div class="code_line">typedef struct tag_sbus_dat {</div><div class="code_line">&nbsp;&nbsp; &nbsp;BYTE &nbsp;StartByte;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch0 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch1 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch2 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch3 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch4 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch5 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch6 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch7 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch8 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch9 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch10 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch11 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch12 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch13 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch14 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WORD ch15 : 11;</div><div class="code_line">&nbsp;&nbsp; &nbsp;BYTE &nbsp;FlagsByte;</div><div class="code_line">&nbsp;&nbsp; &nbsp;BYTE &nbsp;EndByte;</div><div class="code_line">} &nbsp;SBUS_DAT;</div><div class="code_line">#pragma pack(pop)</div><div class="code_line">&nbsp;</div><div class="code_line">typedef union</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp;BYTE byte[25];</div><div class="code_line">&nbsp;&nbsp; &nbsp;SBUS_DAT msg;</div><div class="code_line">} Sbus_msg;</div><div class="code_line">&nbsp;</div><div class="code_line">Sbus_msg Sbus_Data;</div></ol></div></div></div></div><br>
Общее количество бит в структуре должно быть 200, что соответствует 25 байт (размер посылки в SBUS).<br>
Задумка такая: формирую значения всех 16 каналов, и выбрасываю их на USART в виде 25 байтов.<br>
И в обратном направлении: Читаю 25 байтов с USART и тут же получаю 11-битные значения всех 16 каналов.<br>
<br>
Но на 10 канале число не соответствует реальному. И размер структуры :	<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">printf(&quot;sizeof data is %d\n&quot;, sizeof(Sbus_Data));</div></ol></div></div></div></div><br>
Вместо 25 байтов выдает 36.<br>
<br>
Где тут засада, не могу понять... :scratch:]]></description>
        <author>DrUnkard</author>
        <category>Visual C++ / MFC / WTL</category>
      </item>
	
      </channel>
      </rss>
	