Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting from unsigned into signed char in C
    text
    copied!<p>I am converting an input <code>raw pcm</code> stream into <code>mp3</code> using <code>lame</code>. The encoding function within that library returns <code>mp3</code> encoded samples in an array of type <code>unsigned char</code>. This mp3-encoded stream now needs to be placed within an <code>flv</code> container which uses a function that writes encoded samples in <code>char</code> array. My problem is that I am passing the array from <code>lame</code> (of type <code>unsigned char</code>) into the <code>flv</code> library. The following piece of code (only symbolic) illustrates my problem: </p> <pre><code>/* cast from unsigned char to char. */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void display(char *buff, int len) { int i = 0; for(i = 0; i &lt; len; i++) { printf("buff[%d] = %c\n", i, buff[i]); } } int main() { int len = 10; unsigned char* buff = (unsigned char*) malloc(len * sizeof(unsigned char)); int i = 0; for(i = 65; i &lt; (len + 65); i++) { buff[i] = (unsigned char) i; printf("char = %c", (char) i); } printf("Displaying array in main.\n"); for(i = 0; i &lt; len; i++) { printf("buff[%d] = %u\n", i, 'buff[i]'); } printf("Displaying array in func.\n"); display(buff, len); return 0; } </code></pre> <p>My question(s):<br> 1. Is the implicit type conversion in the code below (as demonstrated by passing of <code>buff</code> into function <code>display</code> safe? Is some weird behaviour likely to occur?<br> 2. Given that I have little option but to stick to the functions as they are present, is there a "safe" way of converting an array of <code>unsigned char</code>s into <code>char</code>s?</p>
 

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