{"id":3045,"date":"2018-04-14T00:01:11","date_gmt":"2018-04-14T07:01:11","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=3045"},"modified":"2018-04-07T10:59:36","modified_gmt":"2018-04-07T17:59:36","slug":"from-string-to-binary","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=3045","title":{"rendered":"From String to Binary"},"content":{"rendered":"<p>A function that reads a string of 1s and 0s to generate an integer value output just screams to be called <em>binput()<\/em>. Yet, because my <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=3032\">new version<\/a> of the <em>binbin()<\/em> function (to display a binary value as a string) is called <em>binString()<\/em>, I decided to call its companion function <em>stringBin()<\/em>. Sorry to disappoint you.<br \/>\n<!--more--><br \/>\nThe <em>stringBin()<\/em> function works to process each character in an input string one after the other. The returned <em>int<\/em> value is initialized to zero, which means the processing needs only to set bits: When a <code>'1'<\/code> is encountered in the string, a bit is set; when a <code>'0'<\/code> is encountered, the bit is skipped or left at its current, zero value.<\/p>\n<p>The bitwise OR operator, | (the pipe), sets the bits. I wrote a <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=27\">post on this topic<\/a> a while back. The overall process works similarly to how bits are tested in the <em>binString()<\/em> function, which uses the bitwise AND operator, &amp;. Here&#8217;s the meat of the function:<\/p>\n<pre class=\"screen\">\r\nwhile( *b != '\\n' )\r\n{\r\n    n <<= 1;\r\n    bit = *b=='1' ? 1 : 0;\r\n    if(bit)\r\n        n |= 0x0001;\r\n    b++;\r\n    if( *b=='\\0')\r\n        break;\r\n}<\/pre>\n<p>The input string is referenced by pointer <code>b<\/code>. Variable <code>n<\/code> holds the final integer value. It's shifted to the left one notch, which has no effect on the initial value (zero) for the<em>while<\/em> loop's first spin.<\/p>\n<p>The ternary function tests the character referenced by <code>b<\/code>. If it's a <code>'1'<\/code>, variable <code>bit<\/code> is assigned the value 1, zero otherwise. At this point, I could do further testing to ensure that character <code>*b<\/code> is a <code>'1'<\/code> or <code>'0'<\/code>, but like the <em>scanf()<\/em> function, invalid input interprets as zero. Remember, the <em>scanf()<\/em> function is handy, but not thorough.<\/p>\n<p>If the character <code>'1'<\/code> was encountered and variable <code>bit<\/code> is equal to 1, the statement <code>n |= 0x0001<\/code> is executed and the right-most bit in <code>n<\/code> is set. Pointer <code>b<\/code> is then incremented. A test is made for the null character (string termination), then the loop repeats with <code>n<\/code> shifted left one notch.<\/p>\n<p>After the <em>while<\/em> loop stops, bits in variable <code>n<\/code> are set match the <code>'1'<\/code> characters positioned in the string <code>b<\/code>.<\/p>\n<p>Here's the full code:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint stringBin(char *bin)\r\n{\r\n    char *b;\r\n    unsigned n,bit;\r\n\r\n    b = bin;\r\n    n = 0;\r\n\r\n    while( *b != '\\n' )\r\n    {\r\n        n &lt;&lt;= 1;\r\n        bit = *b=='1' ? 1 : 0;\r\n        if(bit)\r\n            n |= 0x0001;\r\n        b++;\r\n        if( *b=='\\0')\r\n            break;\r\n    }\r\n\r\n    return(n);\r\n}\r\n\r\nint main()\r\n{\r\n    char input[18];\r\n    int v;\r\n\r\n    printf(\"Type up to a 16-digit binary value: \");\r\n    fgets(input,18,stdin);\r\n    v = stringBin(input);\r\n    printf(\"That's %d\\n\",v);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>And some sample runs:<\/p>\n<pre><code>Type up to a 16-digit binary value: 1111111111111111\r\nThat's 65535\r\n\r\nType up to a 16-digit binary value: 01110000110000001\r\nThat's 57729\r\n\r\nType up to a 16-digit binary value: 1111    \r\nThat's 15\r\n\r\nType up to a 16-digit binary value: 11110000\r\nThat's 240<\/code><\/pre>\n<p>The code works when the string is shorter than 16 characters, accurately reflecting the value. And for nonsense values, the code tries:<\/p>\n<pre><code>Type up to a 16-digit binary value: hello\r\nThat's 0\r\n\r\nType up to a 16-digit binary value: 4321\r\nThat's 1<\/code><\/pre>\n<p>The code can also overflow: I set the buffer and input value to account for a 16-character string, plus the newline and null character. Still, it's possible to type an 18-character string as input, in which case the answer is displayed properly, but it's technically an overflow. You can fix this issue on your own, if you like.<\/p>\n<p>It's rare that I've need binary input for any of my code. But I wrote the <em>stringBin()<\/em> function anyway. You never know.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Read a string of ones and zeros to generate an integer value. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3045\">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-3045","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\/3045","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=3045"}],"version-history":[{"count":4,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3045\/revisions"}],"predecessor-version":[{"id":3060,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3045\/revisions\/3060"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3045"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3045"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3045"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}