字符串NSString转换byte ,byte反转得到Nsstring

//

//  ViewController.m

//  qwe

//

//  Created by 余浩 on 17/5/25.

//  Copyright © 2017年 余浩. All rights reserved.

//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

NSString *string = [NSString stringWithFormat:@"2565"];

NSData *testData = [string dataUsingEncoding: NSUTF8StringEncoding];

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

NSLog(@"data=====%@",testData);

Byte *newByte = (Byte *)malloc([testData length]);

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

newByte[i] = testByte[i]^1;

printf("Byte------------%hhu\n",testByte[i]);//%hhu  指定signed char 或 unsigned char    char是1个字节

//  printf("new------------%hhu\n",newByte[i]);

int c = testByte[i] &0xff;  //int类型32

NSLog(@"int c==========%d",c);

};

Byte *nByte = (Byte *)malloc(1);

nByte [0] = -127;

NSLog(@"nBytex==========%x",nByte[0]);

int d = nByte[0] &0xff;//0xff在c语言表示一个十六进制无符号整数,有符号转成无符号

NSLog(@"d==========%d",d);

NSData *data = [NSData dataWithBytes:newByte length:[testData length]];

NSString *stingaa = [[NSString alloc]initWithData:data encoding:(NSUTF8StringEncoding)];

//反转

NSData *testData1 = [stingaa dataUsingEncoding: NSUTF8StringEncoding];

Byte *testByte1 = (Byte *)[testData1 bytes];

Byte *newByte1 = (Byte *)malloc([testData1 length]);

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

newByte1[i] = testByte1[i]^1;

//  printf("newByte1------------%d\n",newByte1[i]);

};

Byte key[1] = {0x32};

NSData *data1 = [NSData dataWithBytes:newByte1 length:[testData length]];

NSString *stingaa1 = [[NSString alloc]initWithData:data1 encoding:(NSUTF8StringEncoding)];

NSLog(@"stingaa1=========%@",stingaa1);

//&(按位与)、|(按位或)、^(按位异或)、~ (按位取反)。

//1个字节是8位,二进制8位:xxxxxxxx 范围从

/**

00000000-11111111,表示0到255。

一位16进制数(用二进制表示是xxxx)最多只表示到15(即对应16进制的F),要表示到255,就还需要第二位。

所以1个字节=2个16进制字符,一个16进制位=0.5个字节

*/

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

你可能感兴趣的:(字符串NSString转换byte ,byte反转得到Nsstring)