Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer, you wouldn't.</p> <p>Long answer, there are a few issues with this. The first big issue is that if we assume bin is a standard array of characters of length "size", then your first print is invalid. The array index is off by 1. Consider the code example:</p> <pre><code>int size = 16; char * bin = new char[size]; for(int i=0; i&lt;size; i++) { bin[i] = 0; } for(int num_bits = size; num_bits&gt;0; num_bits--) { printf("String sub %i is %i\n", num_bits, int(bin[num_bits])); } </code></pre> <p>Which produces:</p> <pre><code>String sub 16 is -3 String sub 15 is 0 String sub 14 is 0 String sub 13 is 0 String sub 12 is 0 String sub 11 is 0 String sub 10 is 0 String sub 9 is 0 String sub 8 is 0 String sub 7 is 0 String sub 6 is 0 String sub 5 is 0 String sub 4 is 0 String sub 3 is 0 String sub 2 is 0 String sub 1 is 0 </code></pre> <p>Judging by the actual output you got, I'm guessing you did something like:</p> <pre><code>int size=16; int * ints = new int[size]; char * bin; //Fill with numbers, not zeros, based on the evidence for(int i=0; i&lt;size; i++) { ints[i] = 20 + i; } //Copy over to character buffer bin = (char*)(void*)&amp;(ints[0]); for(int num_bits = size; num_bits&gt;0; num_bits--) { printf("String sub %i is %i\n", num_bits, int(bin[num_bits])); } </code></pre> <p>That explains the output you saw perfectly. So, I'm thinking your input assumption, that bin points to an array of character zeros, is not true. There are a few really big problems with this, assuming you did something like that.</p> <ol> <li>Your assumption that the memory is all zero is wrong, and you need to explain that or post the real code and we will</li> <li>You can't just treat a memory buffer of integers as characters - a string is made up of one byte characters (typically), integers are 4 bytes, typically</li> <li>Arrays in C++ start at 0, not 1</li> <li>Casting a character to an integer [ int('0') ] does not intelligently convert - the integer that comes out of that is a decimal 48, not a decimal 0 (there is a function atoi that will do that, as well as other better ones, or the other suggestion to use subtraction)</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload