{"id":1906,"date":"2016-05-07T00:01:58","date_gmt":"2016-05-07T07:01:58","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=1906"},"modified":"2016-04-30T09:49:20","modified_gmt":"2016-04-30T16:49:20","slug":"writing-a-wide-bit-field","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=1906","title":{"rendered":"Writing a Wide Bit Field"},"content":{"rendered":"<p>Writing a chunk of bits into an integer at a specific position requires major application of binary manipulation. That sounds impressive and mystical. To put it another way, writing a bit field is like using a stencil to paint a wall: You create the stencil, set it in place, then you slap down the paint.<br \/>\n<!--more--><br \/>\nTo write a bit field, I crafted a function called <em>bit_field_write()<\/em>. It&#8217;s the companion to <em>bit_field_read()<\/em>, covered in <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=1888\">last week&#8217;s Lesson<\/a>. It uses similar arguments:<\/p>\n<p><code>void bit_field_write(char bit, char width, char value, char *byte);<\/code><\/p>\n<p>The <code>bit<\/code> and <code>width<\/code> arguments represent the position and size of the binary chunk to write. <code>bit<\/code> is the position measured from the right-most bit, position 0. <code>width<\/code> is the size of the chunk to be written.<\/p>\n<p>The <code>value<\/code> argument is the chunk of binary data to be written at position <code>bit<\/code>.<\/p>\n<p>Finally, <code>*byte<\/code> is a pointer to the variable that contains the bit field. It&#8217;s a pointer so that the variable is manipulated directly. That way the function need not return a value.<\/p>\n<p>The function itself is divided into four parts:<\/p>\n<p>1. Create the bit mask of a given width.<br \/>\n2. Shift the mask and the value left to the proper bit position.<br \/>\n3. Invert the mask, so that the existing values in the byte are preserved.<br \/>\n4. Write the bit field.<\/p>\n<p>Figure 1 illustrates this process using a field 4 bits wide at position 3 in an 8-bit byte.<\/p>\n<div id=\"attachment_1908\" style=\"width: 560px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1908\" src=\"http:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2016\/05\/0507-figure1-write_bit_field.png\" alt=\"Figure 1. The steps required to write a bit field at a specific position within a byte.\" width=\"550\" height=\"597\" class=\"size-full wp-image-1908\" srcset=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2016\/05\/0507-figure1-write_bit_field.png 550w, https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2016\/05\/0507-figure1-write_bit_field-276x300.png 276w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><p id=\"caption-attachment-1908\" class=\"wp-caption-text\">Figure 1. The steps required to write a bit field at a specific position within a byte.<\/p><\/div>\n<p>First, the bit field and mask are shifted to the proper bit position. Then an <code>^<\/code> (exclusive OR) inverts the mask. The mask is applied to the original value, then a <code>|<\/code> (bitwise OR) set the bits. The following code shows this operation in the function <em>bit_field_write()<\/em>:<\/p>\n<pre class=\"screen\">\r\nvoid bit_field_write(char bit, char width, char value, char *byte)\r\n{\r\n    unsigned char mask;\r\n\r\n    mask = 0;\r\n    while(width--)\r\n    {\r\n        mask = mask &lt;&lt; 1;\r\n        mask |= 1;\r\n    }\r\n\r\n    <span class=\"comments\">\/* position the value and the mask *\/<\/span>\r\n    value = value &lt;&lt; bit;\r\n    mask = mask &lt;&lt; bit;\r\n    <span class=\"comments\">\/* invert the mask *\/<\/span>\r\n    mask ^= 0xFF;\r\n    \/* filter the existing value, reset to zero *\/<\/span>\r\n    *byte &amp;= mask;\r\n    <span class=\"comments\">\/* set the bit field *\/<\/span>\r\n    *byte |= value;\r\n}<\/pre>\n<p>I&#8217;ve written a sample program that uses both <em>bit_field_write()<\/em> and <em>bit_field_read()<\/em>. The code is a bit long; you can view the entire thing <a href=\"http:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2016\/05\/0507.c\"\">here<\/a>, but this is the <em>main()<\/em> function:<\/p>\n<pre class=\"screen\">\r\nint main()\r\n{\r\n    char board,row,column;\r\n\r\n    row = 2;\r\n    column = 4;\r\n    board = 0;\r\n\r\n    bit_field_write(ROW_BIT,FIELD_WIDTH,row-1,&amp;board);\r\n    bit_field_write(COL_BIT,FIELD_WIDTH,column-1,&amp;board);\r\n\r\n    printf(\"The Queen is at row %d, column %d\\n\",\r\n            bit_field_read(ROW_BIT,FIELD_WIDTH,board)+1,\r\n            bit_field_read(COL_BIT,FIELD_WIDTH,board)+1\r\n            );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>Two calls are made to <em>bit_field_write()<\/em>, which set the Queen&#8217;s row and column position. Inside the <em>printf()<\/em> function, the <em>bit_field_read()<\/em> functions report those positions. The <code>row<\/code> and <code>column<\/code> variables are adjusted to account for row 0 and column 0. Here is sample output:<\/p>\n<pre><code>The Queen is at row 2, column 4<\/code><\/pre>\n<p>The <em>bit_field_read()<\/em> and <em>bit_field_write()<\/em> functions need modification if you plan on reading and writing to larger integer variables, yet they would still function the same. As I wrote in <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=1888\">last week&#8217;s Lesson<\/a>, I would definitely add bounds checking to the functions if I were to create and release a library. Feel free to add that code to the functions on your own.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Insert a chunk of bits into an integer value at a specific position. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=1906\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-1906","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1906","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1906"}],"version-history":[{"count":5,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1906\/revisions"}],"predecessor-version":[{"id":1924,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1906\/revisions\/1924"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1906"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1906"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1906"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}