关于 NSData 的数据类型(2进制,16进制之间)及深入剖析(转)

时间:2023-12-17 09:08:02
. NSData 与 NSString
NSData-> NSString
NSString *aString = [[NSString alloc initWithData:adataencoding:NSUTF8StringEncoding]; NSString->NSData
NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding]; .NSData 与 Byte
NSData-> Byte数组
NSString *testString = @"";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
for(int i=;i<[testData length];i++){
  printf("testByte = %d\n",testByte);
}

Byte数组->
NSData
Byte byte[] = {,,,,,,,,,,,,,,,,,,,,,,,};
NSData *adata = [[NSData alloc] initWithBytes:byte length:]; Byte数组->16进制数
Byte *bytes = (Byte *)[aData bytes];
NSString *hexStr=@"";
for(int i=;i<[encryData length];i++)
{
  NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes&0xff];///16进制数
  if([newHexStr length]==){
    hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
  }else{
    hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
  }
}
NSLog(@"bytes 的16进制数为:%@",hexStr);

16进制数->Byte数组
// 将16进制数据转化成Byte 数组
NSString *hexString = @"3e435fab9c34891f"; //16进制字符串
int j=;
Byte bytes[]; ///3ds key的Byte 数组, 128位
for(int i=;i<[hexString length];i++)
{
  int int_ch; /// 两位16进制数转化后的10进制数
  unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
  int int_ch1;
  if(hex_char1 >= '' && hex_char1 <='')
    int_ch1 = (hex_char1-)*; //// 0 的Ascll - 48
  else if(hex_char1 >= 'A' && hex_char1 <='F')
    int_ch1 = (hex_char1-)*; //// A 的Ascll - 65
  else
    int_ch1 = (hex_char1-)*; //// a 的Ascll - 97
    i++;
    unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
    int int_ch2;
  if(hex_char2 >= '' && hex_char2 <='')
    int_ch2 = (hex_char2-); //// 0 的Ascll - 48
  else if(hex_char1 >= 'A' && hex_char1 <='F')
    int_ch2 = hex_char2-; //// A 的Ascll - 65
  else
    int_ch2 = hex_char2-; //// 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:];
NSLog(@"newData=%@",newData); . NSData 与 UIImage NSData->UIImage
UIImage *aimage = [UIImage imageWithData: imageData];
//例:从本地文件沙盒中取图片并转换为NSData
NSString *path = [[NSBundle mainBundle bundlePath];
NSString *name = [NSString stringWithFormat:@"ceshi.png"];
NSString *finalPath = [path stringByAppendingPathComponent:name];
NSData *imageData = [NSData dataWithContentsOfFile: finalPath];
UIImage *aimage = [UIImage imageWithData: imageData];

UIImage-> NSData
NSData *imageData = UIImagePNGRepresentation(aimae);