之前在java上写过String转为byte数组的代码,后来在开发iPhone程序的时候,发现也需要把NSString转为byte数组,并且需要达到跟java程序兼容。但是发现java自身的默认编码机制为iso-8859-1,而ios的默认编码机制为utf-8,所以直接编码并不能达到两者兼容的问题。后来查阅相关资料,最后解决了编码兼容的问题,而且中英文都通用。
如下为java代码:
String str = "你好啊,aBc!";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputstream = new DataOutputStream(baos);
outputstream.writeChars(str);
byte[] contents = baos.toByteArray();
for (int i = 0; i < contents.length; i++) {
System.out.println("contents:"+contents[i]);
}
最后打印为:
contents:79
contents:96
contents:89
contents:125
contents:85
contents:74
contents:0
contents:44
contents:0
contents:97
contents:0
contents:66
contents:0
contents:99
contents:0
contents:33
ios代码:
NSString *str = @"你好啊,aBc!";
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(NSUTF16BigEndianStringEncoding);
NSData *data = [str dataUsingEncoding:enc];
Byte *byte = (Byte *)[data bytes];
for (int i=0 ; i<[data length]; i++) {
NSLog(@"byte = %d",byte[i]);
}
最后打印结果为
2012-07-19 10:07:46.967 encoding[593:f803] byte = 79
2012-07-19 10:07:46.969 encoding[593:f803] byte = 96
2012-07-19 10:07:46.969 encoding[593:f803] byte = 89
2012-07-19 10:07:46.970 encoding[593:f803] byte = 125
2012-07-19 10:07:46.970 encoding[593:f803] byte = 85
2012-07-19 10:07:46.970 encoding[593:f803] byte = 74
2012-07-19 10:07:46.970 encoding[593:f803] byte = 0
2012-07-19 10:07:46.971 encoding[593:f803] byte = 44
2012-07-19 10:07:46.971 encoding[593:f803] byte = 0
2012-07-19 10:07:46.971 encoding[593:f803] byte = 97
2012-07-19 10:07:46.971 encoding[593:f803] byte = 0
2012-07-19 10:07:46.972 encoding[593:f803] byte = 66
2012-07-19 10:07:46.972 encoding[593:f803] byte = 0
2012-07-19 10:07:46.972 encoding[593:f803] byte = 99
2012-07-19 10:07:46.972 encoding[593:f803] byte = 0
2012-07-19 10:07:46.973 encoding[593:f803] byte = 33
编码一致!点赞
参考文档:http://blog.csdn.net/miemie1320/article/details/7761848
网友评论