{"id":3956,"date":"2021-11-12T17:58:55","date_gmt":"2021-11-12T17:58:55","guid":{"rendered":"https:\/\/www.gubatron.com\/blog\/?p=3956"},"modified":"2021-11-12T22:39:02","modified_gmt":"2021-11-12T22:39:02","slug":"accessing-and-manipulating-a-32bit-integer-as-an-array-in-c-thanks-to-union","status":"publish","type":"post","link":"https:\/\/www.gubatron.com\/blog\/accessing-and-manipulating-a-32bit-integer-as-an-array-in-c-thanks-to-union\/","title":{"rendered":"Accessing and manipulating a 32bit integer as a byte array in C++ using unions"},"content":{"rendered":"<p>I don&#8217;t think I&#8217;ve ever used <code>union<\/code> for anything, but today I came across a very interesting use case to avoid bit-shifting tricks when dealing with data embedded in numbers.<\/p>\n<p><strong>What&#8217;s a union?<\/p>\n<p><\/strong><a href=\"https:\/\/docs.microsoft.com\/en-us\/cpp\/cpp\/unions?view=msvc-170\">Microsoft defines it this way<\/a><\/p>\n<blockquote><p>A\u00a0<code>union<\/code>\u00a0is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members. It also means that no matter how many members a union has, it always uses only enough memory to store the largest member.<strong><br \/>\n<\/strong><\/p><\/blockquote>\n<p>Example:<\/p>\n<p>[pastacode lang=&#8221;cpp&#8221; manual=&#8221;union%20IntChar%20%7B%0A%20%20%20%20unsigned%20int%20i%3B%0A%20%20%20%20char%20c%3B%0A%7D%3B%0A%0AIntChar%20foo%3B%0Afoo.i%20%3D%2065%3B%20%2F%2F%20&#8217;A&#8217;%20in%20ASCII%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0Aprintf(%22i%3A%20%25d%2C%20c%3A%20%25c%5Cn%22%2C%20foo.i%2C%20foo.c)%3B%0A%0A%2F%2F%20i%3A%2065.%20c%3A%20A&#8221; message=&#8221;Represent an integer as a char, or char as int&#8221; highlight=&#8221;&#8221; provider=&#8221;manual&#8221;\/]<\/p>\n<p>We can also do the same with an anonymous union, and directly use the variables, which will change each other&#8217;s values<\/p>\n<p><span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_start\"><span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_start\">\ufeff<\/span>\ufeff<\/span>[pastacode lang=&#8221;cpp&#8221; manual=&#8221;union%20%7B%0A%20%20unsigned%20int%20i%3B%0A%20%20char%20c%3A%0A%7D%0Ac%3D&#8217;A&#8217;%3B%0Aprintf(%22i%3A%20%25d%2C%20f%3A%20%25c%5Cn%22%2C%20i%2C%20c)%3B%0A%2F%2F%20i%3A%2065%2C%20c%3A%20A&#8221; message=&#8221;&#8221; highlight=&#8221;&#8221; provider=&#8221;manual&#8221;\/]<span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_end\">\ufeff<\/span><\/p>\n<p><strong>Let&#8217;s apply this feature to a 32 bit integer (4 bytes) and a 4 byte array<\/p>\n<p><\/strong>This I believe might come in handy if you need to use integers as arrays of 8 bit numbers because you can use the array &#8216;[]&#8217; operator to access the individual bytes in the number without having to do bit shifting tricks (&gt;&gt;,&lt;&lt;,&amp;,|) to extract them or manipulate them<\/p>\n<p>[pastacode lang=&#8221;cpp&#8221; path_id=&#8221;51909d0741b8901a8e59d704104c2ef7&#8243; file=&#8221;int_as_array.cpp&#8221; highlight=&#8221;&#8221; lines=&#8221;&#8221; provider=&#8221;gist&#8221;\/]<\/p>\n<p><strong>\u00a0<\/strong><span data-mce-type=\"bookmark\" style=\"display: inline-block; width: 0px; overflow: hidden; line-height: 0;\" class=\"mce_SELRES_end\">\ufeff<\/span><\/p>\n<p>Build and output:<\/p>\n<pre><code>$ g++ int_as_array.cpp &amp;&amp; .\/a.out\na: 0xaabbccdd\na[0]: 0xdd\na[1]: 0xcc\na[2]: 0xbb\na[3]: 0xaa\na: 0xaabbccff\n<\/code><\/pre>\n<h2>DO NOT USE THIS TECHNIQUE IN PRODUCTION CODE:<\/h2>\n<p>Here&#8217;s a word about this trick from my very esteemed friend (and elite coder) <a href=\"https:\/\/twitter.com\/virus_dave\">Dave Nicponski<\/a><\/p>\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\">\n<p lang=\"en\" dir=\"ltr\">Doing this correctly is highly dependent upon following and understanding the language spec, fyi<\/p>\n<p>&mdash; \ud83d\udc49 @virus_dave@mastodon.social (@virus_dave) <a href=\"https:\/\/twitter.com\/virus_dave\/status\/1459223290044723201?ref_src=twsrc%5Etfw\">November 12, 2021<\/a><\/p><\/blockquote>\n<p><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><\/p>\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\">\n<p lang=\"en\" dir=\"ltr\">I should clarify.  You basically CANNOT do this safely in general. Specifically, &quot;It&#39;s undefined behavior to read from the member of the union that wasn&#39;t most recently written.&quot; (with very restrictive exceptions).  You may see &quot;reasonable&quot; behavior depending on the compiler&#8230;<\/p>\n<p>&mdash; \ud83d\udc49 @virus_dave@mastodon.social (@virus_dave) <a href=\"https:\/\/twitter.com\/virus_dave\/status\/1459278075632525313?ref_src=twsrc%5Etfw\">November 12, 2021<\/a><\/p><\/blockquote>\n<p><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><\/p>\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\">\n<p lang=\"en\" dir=\"ltr\">&#8230;used, which may provide additional guarantees not present in the C++ spec, but it&#39;s not portable, and a compliant compiler would be allowed to do just about anything it wants to break your program (like return a zero value on the read, or skip the preceding write, etc).<\/p>\n<p>&mdash; \ud83d\udc49 @virus_dave@mastodon.social (@virus_dave) <a href=\"https:\/\/twitter.com\/virus_dave\/status\/1459278341777903616?ref_src=twsrc%5Etfw\">November 12, 2021<\/a><\/p><\/blockquote>\n<p><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I don&#8217;t think I&#8217;ve ever used union for anything, but today I came across a very interesting use case to avoid bit-shifting tricks when dealing with data embedded in numbers. What&#8217;s a union? Microsoft defines it this way A\u00a0union\u00a0is a user-defined type in which all members share the same memory location. This definition means that [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[15],"tags":[1647,1648],"class_list":["post-3956","post","type-post","status-publish","format-standard","hentry","category-code","tag-cpp","tag-union"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5Unzf-11O","jetpack-related-posts":[{"id":3656,"url":"https:\/\/www.gubatron.com\/blog\/code-arduino-4-bit-led-counter\/","url_meta":{"origin":3956,"position":0},"title":"[CODE] Arduino 4 BIT LED binary counter","author":"gubatron","date":"January 11, 2017","format":false,"excerpt":"Here's my \"Hello World\" on Arduino. A 4-bit binary counter for arduino. If you add another LED on the 5th pin, then it can count from 0 to 31 (32 values) Circuit wired by @KataySantos [pastacode lang=\"c\" manual=\"int%20counter%20%3D%20-1%3B%0Aint%20MAX_VALUE%20%3D%2016%3B%0A%0Avoid%20updateLED(int%20pin%2C%20int%20bit%2C%20int%20ctr)%20%7B%0A%20%20digitalWrite(pin%2C%20(ctr%20%26%20(1%3C%3Cbit))%20%3D%3D%20(1%3C%3Cbit)%20%3F%20HIGH%20%3A%20LOW)%3B%0A%7D%0Avoid%20setup()%20%7B%0A%20%20%2F%2F%20this%20runs%20once%0A%20%20pinMode(1%2C%20OUTPUT)%3B%0A%20%20pinMode(2%2C%20OUTPUT)%3B%0A%20%20pinMode(3%2C%20OUTPUT)%3B%0A%20%20pinMode(4%2C%20OUTPUT)%3B%0A%7D%0A%0Avoid%20loop()%20%7B%0A%20%20%2F%2F%20this%20runs%20repeatedly%0A%20%20counter%20%3D%20(counter%20%2B%201)%20%25%20MAX_VALUE%3B%0A%20%20updateLED(1%2C%200%2C%20counter)%3B%0A%20%20updateLED(2%2C%201%2C%20counter)%3B%0A%20%20updateLED(3%2C%202%2C%20counter)%3B%0A%20%20updateLED(4%2C%203%2C%20counter)%3B%0A%20%20delay(500)%3B%0A%7D\" message=\"\" highlight=\"\" provider=\"manual\"\/]","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3616,"url":"https:\/\/www.gubatron.com\/blog\/codejava-argb_8888-pixel-abstraction\/","url_meta":{"origin":3956,"position":1},"title":"[CODE\/JAVA] ARGB_8888 Pixel Abstraction","author":"gubatron","date":"December 4, 2016","format":false,"excerpt":"This is one of the ways you can decode Pixel colors out of the integers you get from Android Pixels. ARGB_8888, stands for Alpha, Reg, Green, Blue. The 8's stand for the number of bits per channel. In Android, signed int's are used to represent pixel's alpha\/color information. Since Android's\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3651,"url":"https:\/\/www.gubatron.com\/blog\/codephp-jpgraph-how-to-output-your-graph-as-a-base64-encoded-image\/","url_meta":{"origin":3956,"position":2},"title":"[CODE\/PHP] JpGraph: How to output your graph as a base64 encoded image","author":"gubatron","date":"January 11, 2017","format":false,"excerpt":"Some times you just want to output the image created by your $graph object without having to create a separate .php script that would need to receive a bunch of parameters. Here's a function you can pass your $graph object right before the $graph->Stroke(); call [pastacode lang=\"php\" manual=\"function%20graphInSrc(%24graph%2C%20%24width%2C%20%24height)%20%7B%0A%20%20%24img%20%3D%20%24graph-%3EStroke(_IMG_HANDLER)%3B%0A%20%20ob_start()%3B%0A%20%20imagepng(%24img)%3B%0A%20%20%24img_data%20%3D%20ob_get_contents()%3B%0A%20%20ob_end_clean()%3B%0A%0A%20%20echo%20'%3Cimg%20width%3D%22'.%24width.'%22%20height%3D%22'.%24height.'%22%20src%3D%22data%3Aimage%2Fpng%3Bbase64%2C'.base64_encode(%24img_data).'%22%2F%3E'%3B%0A%7D\" message=\"\" highlight=\"\"\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3388,"url":"https:\/\/www.gubatron.com\/blog\/how-to-create-a-list-that-holds-different-object-types-using-void-in-c\/","url_meta":{"origin":3956,"position":3},"title":"How to create a list that holds different object types using `void*` in C.","author":"gubatron","date":"April 5, 2015","format":false,"excerpt":"I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out. In this exercise I store\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2015\/04\/Screen-Shot-2015-12-20-at-7.05.10-PM.png?fit=1200%2C438&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2015\/04\/Screen-Shot-2015-12-20-at-7.05.10-PM.png?fit=1200%2C438&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2015\/04\/Screen-Shot-2015-12-20-at-7.05.10-PM.png?fit=1200%2C438&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2015\/04\/Screen-Shot-2015-12-20-at-7.05.10-PM.png?fit=1200%2C438&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2015\/04\/Screen-Shot-2015-12-20-at-7.05.10-PM.png?fit=1200%2C438&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":3164,"url":"https:\/\/www.gubatron.com\/blog\/how-to-have-a-play-framework-app-autostart-during-boot-on-elastic-beanstalk-centos-ec2-instances\/","url_meta":{"origin":3956,"position":4},"title":"How to have a Play framework app autostart during boot on Elastic Beanstalk CentOS ec2 instances","author":"gubatron","date":"September 27, 2013","format":false,"excerpt":"So you've created an Elastic Beanstalk environment, you have a play framework distribution which you've created using play dist (either on your local environment, or right there on the server, whatever you prefer) play dist outputs a my-app-1.0.zip file which has a self-contained version of your app with all the\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3793,"url":"https:\/\/www.gubatron.com\/blog\/solving-received-fatal-alert-handshake_failure-error-when-performing-https-connections-on-a-custom-made-jre-with-jlink\/","url_meta":{"origin":3956,"position":5},"title":"Solving &#8220;Received fatal alert: handshake_failure&#8221; error when performing HTTPS connections on a custom made JRE with jlink","author":"gubatron","date":"April 25, 2019","format":false,"excerpt":"TL; Tell me already what to do: Add the jdk.crypto.cryptoki module to the list of --add-modules parameter to your jlink command invocation If you're reading this you're one of the few developers out there that wanted to distribute a java 9+ app (using either jdk 9, jdk 10, jdk 11\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2019\/04\/dragon.jpg?fit=1200%2C797&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2019\/04\/dragon.jpg?fit=1200%2C797&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2019\/04\/dragon.jpg?fit=1200%2C797&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2019\/04\/dragon.jpg?fit=1200%2C797&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2019\/04\/dragon.jpg?fit=1200%2C797&ssl=1&resize=1050%2C600 3x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3956","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/comments?post=3956"}],"version-history":[{"count":8,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3956\/revisions"}],"predecessor-version":[{"id":3964,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3956\/revisions\/3964"}],"wp:attachment":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/media?parent=3956"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/categories?post=3956"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/tags?post=3956"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}