第三方工具类

NSString NSData Byte等互转

2016-05-03  本文已影响6011人  一个城市猎人

```objc

NSString *testString = @"1234567890";

NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];

Byte *testByte = (Byte *)[testData bytes];

for(int i=0;i<[testData length];i++)

printf("testByte = %d\n",testByte);

   NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];

   NSUInteger len = [data length];

       Byte *byteData = (Byte*)malloc(len);

       memcpy(byteData, [data bytes], len);

       for (int i = 0; i

           NSLog(@"%d",byteData [i] );

Objective-C NSString NSData Byte等转换

//整形转NSString,其他数字类型类似

inti= 123;

NSString*str = [NSString stringWithFormat:@"%d", i];

// NSSting转整形,转其他数字类型类似

i= [str intValue];

float f = [str floatValue];

{

// NSData --> NSString

Byte array[] = {0, 0, 0, 0};

NSData*data = [NSData dataWithBytes: array length:sizeof(array)];

NSString*string = [[NSString alloc]initWithData: data encoding:NSUTF8StringEncoding];

}

{

// NSString --> NSData

NSString*string =@"Hello,World!";

NSData*data = [string dataUsingEncoding:NSUTF8StringEncoding];

}

{

// NSData --> Byte

Byte array[] = {0, 0, 0, 0};

NSData*data = [NSData dataWithBytes: array length:sizeof(array)];

Byte*bytes = (Byte*)[data bytes];

}

{

// NSString --> hex

NSString*string =@"1a1b1c1d";

constchar*buf = [string UTF8String];

NSMutableData*data = [NSMutableData data];

if(buf)

{

uint32_tlen =strlen(buf);

charsingleNumberString[3] = {'\0', '\0', '\0'};

uint32_tsingleNumber = 0;

for(uint32_ti = 0 ; i < len; i+=2)

{

if( ((i+1) < len) &&isxdigit(buf[i]) && (isxdigit(buf[i+1])) )

{

singleNumberString[0] = buf[i];

singleNumberString[1] = buf[i + 1];

sscanf(singleNumberString,"%x", &singleNumber);

uint8_ttmp = (uint8_t)(singleNumber & 0x000000FF);

[dataappendBytes:(void*)(&tmp)length:1];

}

else

{

break;

}

}

}

}

原文http://blog.csdn.net/jjunjoe/article/details/7546790

NSdata 与 NSString,Byte数组,UIImage 的相互转换---ios开发 Objective-C

http://blog.sina.com.cn/s/blog_45e2b66c010102va.html

Object-C 中各数据类型转换 NSData转NSString,Byte,UIImage

http://blog.csdn.net/bailu66/article/details/7665357

       }

```

上一篇 下一篇

猜你喜欢

热点阅读