如何将 NSData 转换为 const char *?
How to convert an NSData to const char *?
我正在尝试将带有音频数据的 NSData 对象转换为 const char *。我必须这样做,因为我尝试调用的 API 需要 const char *。但我无法这样做
const char * stream = [data bytes]; //won't compile
还有
const char * stream = (const char *)[data bytes];
会编译,但出于某种原因只有前 2 个字节。
提前致谢。
假设 const char*
指向一个以 null 结尾的字符串,因此 NSData
对象中的第一个空字符将终止该字符串。
使用强制转换执行此转换没有上下文意义,因为它只是要求 API 将 NSData 解释为 const char*
。
如果您试图将 NSData 传递给需要 const char*
的 API,您可能使用了错误的 API,或者您需要重新- 在使用 API.
之前对您的数据进行编码
更新:根据OP的评论,他想对数据进行编码以便稍后解码。
对此有多种不同的解决方案,但一种简单的可能性是 base64
使用 API method. You could then base64
decode it using the symmmetric API method. You could then convert the resulting NSString
to const char*
using the approach suggested in this answer 对数据进行编码。
假设你加载的NSData原本是一个字符串,你可以这样试试:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
const char *chars = [string UTF8String];
这将首先将 NSData 转换为 NSString,然后将 NSString 转换为 const char 指针。
更新
由于您只是尝试将数据编码为十六进制字符串,请查看此线程:
How to convert an NSData into an NSString Hex string?
它应该看起来像这样:
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i)
{
[sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
}
const char *chars = [sbuf UTF8String];
我正在尝试将带有音频数据的 NSData 对象转换为 const char *。我必须这样做,因为我尝试调用的 API 需要 const char *。但我无法这样做
const char * stream = [data bytes]; //won't compile
还有
const char * stream = (const char *)[data bytes];
会编译,但出于某种原因只有前 2 个字节。
提前致谢。
const char*
指向一个以 null 结尾的字符串,因此 NSData
对象中的第一个空字符将终止该字符串。
使用强制转换执行此转换没有上下文意义,因为它只是要求 API 将 NSData 解释为 const char*
。
如果您试图将 NSData 传递给需要 const char*
的 API,您可能使用了错误的 API,或者您需要重新- 在使用 API.
更新:根据OP的评论,他想对数据进行编码以便稍后解码。
对此有多种不同的解决方案,但一种简单的可能性是 base64
使用 API method. You could then base64
decode it using the symmmetric API method. You could then convert the resulting NSString
to const char*
using the approach suggested in this answer 对数据进行编码。
假设你加载的NSData原本是一个字符串,你可以这样试试:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
const char *chars = [string UTF8String];
这将首先将 NSData 转换为 NSString,然后将 NSString 转换为 const char 指针。
更新
由于您只是尝试将数据编码为十六进制字符串,请查看此线程:
How to convert an NSData into an NSString Hex string?
它应该看起来像这样:
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i)
{
[sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
}
const char *chars = [sbuf UTF8String];