ios - 为什么在Objective C中转换为字符串时char数组会插入尾随字符?
<p><p>我正在尝试在 NSString 上编写一个快速类别来对字符串的内容进行 base64 编码。一切似乎都很好,除了在生成的字符串的尾端出现了额外的字符。谁能解释一下为什么下面的代码会产生下面的输出?</p>
<p>来源:</p>
<pre><code>const char base64CharSet = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
const char *input = "Hello, World!";
int length = strlen(input);
int outlen = (length / 3) * 4;
int modlen = length % 3;
int rawlen = length - modlen;
if (modlen != 0)
outlen += 4;
char output;
char inbuf, outbuf;
int inpos = 0, outpos = 0;
for (outpos = 0, inpos = 0; inpos < rawlen; inpos += 3) {
for (int i = 0; i <3; i++) {
int j = inpos + i;
inbuf = j < length ? input : 0;
}
outbuf =(inbuf & 0xFC) >> 2;
outbuf = ((inbuf & 0x03) << 4) | ((inbuf & 0xF0) >> 4);
outbuf = ((inbuf & 0x0F) << 2) | ((inbuf & 0xC0) >> 6);
outbuf =(inbuf & 0x3F);
output = base64CharSet];
output = base64CharSet];
output = base64CharSet];
output = base64CharSet];
}
if (modlen > 0) {
char modbuf = {0, 0, 0};
for (int i = 0; i < modlen; i++) {
int j = rawlen + i;
modbuf = input;
}
outbuf =(modbuf & 0xFC) >> 2;
outbuf = ((modbuf & 0x03) << 4) | ((modbuf & 0xF0) >> 4);
outbuf = ((modbuf & 0x0F) << 2) | ((modbuf & 0xC0) >> 6);
outbuf =(modbuf & 0x3F);
output = base64CharSet];
output = base64CharSet];
output = modlen == 2 ? base64CharSet] : '=';
output = '=';
}
NSLog(@"Input: '%s', Length: %zd", input, strlen(input));
NSLog(@"Output: '%s', Length: %zd, Expected Length: %d", output, strlen(output), outlen);
</code></pre>
<p>输出:</p>
<pre><code>2013-03-19 14:46:51.568 Sandbox Input: 'Hello, World!', Length: 13
2013-03-19 14:46:51.569 Sandbox Output: 'SGVsbG8sIFdvcmxkIQ==wä]', Length: 23, Expected Length: 20
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><pre><code>2013-03-19 14:46:51.569 Sandbox Output: 'SGVsbG8sIFdvcmxkIQ==wä]', Length: 23, Expected Length: 20
</code></pre>
<p>最后的 goober 是因为您没有 NULL 终止输出缓冲区。 C 字符串要求字符串中最后一个字符之后的字符为 0(全为 0 位,而不是 ASCII "0":)。</p>
<hr/>
<blockquote>
<p>... appending to a full array would raise an exception ...</p>
</blockquote>
<p>欢迎来到 C!该语言类似于用剪刀奔跑。即使跌倒,也不会受伤。可能不会。</p>
<p>在这种情况下,您实际上并没有写入 NULL 字节,因此,C 字符串的打印只是读取您的字符串数组之后发生在堆栈上的任何内容。我没有审核代码以确定缓冲区的大小是否正确。 </p>
<p>假设您的所有数学运算都是正确的,您可以将缓冲区分配为比编码所需的长一个字节,然后将终止符放在那里。</p>
<pre><code>char output;
output = 0;
</code></pre></p>
<p style="font-size: 20px;">关于ios - 为什么在Objective C中转换为字符串时char数组会插入尾随字符?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/15508231/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/15508231/
</a>
</p>
页:
[1]