User Tools

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
user:embedded_c_code_doesn_t_have_to_be_ugly [2020/05/11 17:15] – [4. Bit manipulations vs. structured data] Igor Yefmovuser:embedded_c_code_doesn_t_have_to_be_ugly [2020/05/11 17:18] – [4. Bit manipulations vs. structured data] Igor Yefmov
Line 101: Line 101:
  
 Here's a more concrete example: working with 16/32 bit integers, where depending on the context it is either a CPU-addressable word, or a stream of bytes on the wire (be it USB or I²C). Traditionally that would result in the 1970's style code like this: Here's a more concrete example: working with 16/32 bit integers, where depending on the context it is either a CPU-addressable word, or a stream of bytes on the wire (be it USB or I²C). Traditionally that would result in the 1970's style code like this:
-<code C>uint32_t byteAddress 12356;+<code C>uint32_t = pageAddress * glSpiPageSize;
 uint8_t location[4]; uint8_t location[4];
 location[1] = (byteAddress >> 16) & 0xFF; /* MS byte */ location[1] = (byteAddress >> 16) & 0xFF; /* MS byte */
Line 129: Line 129:
 /////////////////////////////////// ///////////////////////////////////
  
-PackedUint16 pageAddress = {12356};+PackedUint32 byteAddress = {pageAddress * glSpiPageSize};
 uint8_t location[4] = {};      /* uninitialized memory is evil */ uint8_t location[4] = {};      /* uninitialized memory is evil */
 location[1] = byteAddress.h.l; /* compiler error, of course - must be PackedUint32, not 16 */ location[1] = byteAddress.h.l; /* compiler error, of course - must be PackedUint32, not 16 */
Line 135: Line 135:
 location[3] = byteAddress.l.l; /* LS byte */ location[3] = byteAddress.l.l; /* LS byte */
  
-/* alternatively the code above can be written even more compactly and more to-the-point, clearly expressing the intent: +/* alternatively the code above can be written much more to-the-point, clearly expressing the intent  */ 
-const uint8_t * const location = pageAddress.a; +const uint8_t * const location_arr = pageAddress.a;</code>
- */ +
-</code>+
  
  

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also, you acknowledge that you have read and understand our Privacy Policy. If you do not agree, please leave the website.

More information