- (void)viewDidLoad {
[super viewDidLoad];
//注意,中文的编码集是Unicode 一个中文有三个字节
_myStr1 = @"wukeng please cheer 我";
[self transform];
[self sixthTobyes];
}
1.字符串转数据
NSData *data = [_myStr1 dataUsingEncoding:NSUTF8StringEncoding];
2.数据转字节数组
Byte *bytes = (Byte *)[data bytes];
for (int i = 0; i < data.length; i++) {
NSLog(@"%hhu",bytes[i]);
//字节数组转换成字符
NSData *d1 = [NSData dataWithBytes:bytes length:i+1];
NSString *str = [[NSString alloc] initWithData:d1 encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
3.字节数组转换成16进制数
NSString *hexStr=@"";
for(int i=0;i<[data length];i++)
{
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
if([newHexStr length]==1)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
NSLog(@"bytes 的16进制数为:%@",hexStr);
4.16进制数转换成字节数组
int j=0;
Byte bytes[hexString.length / 2];
for(int i=0;i<[hexStr length];i++)
{
int int_ch; /// 两位16进制数转化后的10进制数
unichar hex_char1 = [hexStr characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
int int_ch1;
if(hex_char1 >= '0' && hex_char1 <='9')
{
int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48
}
else if(hex_char1 >= 'A' && hex_char1 <='F')
{
int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
}
else
{
int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
}
i++;
unichar hex_char2 = [hexStr characterAtIndex:i]; ///两位16进制数中的第二位(低位)
int int_ch2;
if(hex_char2 >= '0' && hex_char2 <='9')
{
int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
}
else if(hex_char1 >= 'A' && hex_char1 <='F')
{
int_ch2 = hex_char2-55; //// A 的Ascll - 65
}
else
{
int_ch2 = hex_char2-87; //// a 的Ascll - 97
}
int_ch = int_ch1+int_ch2;
NSLog(@"int_ch=%d",int_ch);
bytes[j] = int_ch; ///将转化后的数放入Byte数组里
j++;
}
NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexStr.length / 2];
NSLog(@"newData=%@",newData);
swift版本的代码建下面
class ViewController: UIViewController {
var myStr = "wukeng cheer please"
override func viewDidLoad() {
super.viewDidLoad()
transform()
}
}
//字符串转数据,数据转字符串,数据转字节数组,字节数组转数据
extension ViewController{
func transform() {
//字符串转数据
let d1 = myStr.data(using: .utf8, allowLossyConversion: true)
print(d1!)
//数据转换成字符串
let string = NSString.init(data: d1!, encoding: String.Encoding.utf8.rawValue)
print(string!)
//数据转换成字节数组
let bytes = [UInt8](d1!)
print(bytes)
//字节数组转数据
let mutData = NSMutableData()
mutData.append(bytes, length: bytes.count)
print(mutData)
//字节数组转16进制字符串
let str2 = bytesToHexStr(bytes: bytes)
print(str2)
}
}
extension ViewController{
//字节数组转16进制字符串
func bytesToHexStr(bytes : [UInt8]) -> String {
var hexStr = ""
for index in 0...bytes.count-1 {
let newHexStr = NSString.init(format: "%x", bytes[index]&0xff)
if newHexStr.length == 1 {
hexStr = NSString.init(format: "%@0%@", hexStr,newHexStr) as String
}
else{
hexStr = NSString.init(format: "%@%@", hexStr,newHexStr) as String
}
}
return hexStr
}
}
以上就是一些简单的数据转换希望对大家有帮助。