2015-01-05 3 views
0

NSString을 바이트로 변환하는 것과 관련된 질문이 있습니다.NSString을 바이트로 변환

내 질문은 바이트에서 NSData를 만들고 싶습니다. 여기 아래 코드에서 모든 것이 잘되지만 combinedStr 대신 int variables.ie 0101,0102, ...을 전달해야합니다.

@ "0101", @ "0102"와 같은 문자열 변수가 나타납니다. .includestring.In의 경우에 변수에 combinestring을 int로 변환하면 101,102라는 값을 제공하지만 ... 0101,0102가 필요합니다. 아무도이 문제를 해결할 수 있도록 도와 주시겠습니까?

NSData *valData = [NSData dataWithBytes:(Byte[]){254,1,200,0.5,combinedstring,0.4,1} length:7]; 

combinedstring은 String 및 variable입니다. combinestring 대신 int 값만 전달할 수 있습니다.

내 질문에 당신은 -dataUsingEncoding:allowLossyConversion: 또는 -getCString:maxLength:encoding:(NSStringEncoding)encoding와 C 배열에 NSData의 인스턴스에 NSString의 인스턴스를 변환 할 수 있습니다

+0

너무이 답변에 보라 - http://stackoverflow.com/questions/27700431/iosconvert-string-to-hexadecimal-array/27700913#27700913 – Kampai

답변

2

명확하지 않은 경우 알려 주시기 바랍니다.

두 경우 모두 개체 resp에 대한 포인터가 있습니다. char[]. 해당 포인터를 Byte 배열에 넣으면 포인터를 변환하고 해당 값을 복사하지만 참조 된 데이터는 복사하지 않습니다.

추가적으로 : Byte[]0.4 (제로 기간 -4) 및 0.5 (제로 기간 -5)을 저장하려고합니다. 이 일을하지 않을 것입니다, 당신은 아마 기대합니다. 값을 Byte (정수 유형!) 유형의 값으로 변환하고 해당 값을 저장합니다. 255보다 큰 정수 값도 변환됩니다.

따라서 가변 데이터 객체를 사용하고 다른 유형의 이진 표현을 개별적으로 연결해야합니다.

예 :

NSData *stringData = [combinedString dataUsingEncoding:… allowLossyConversion:NO]; 
if (stringData == nil) 
{ 
    // error handling 
} 


NSMutableData *data = [NMutableData new]; 
Byte *byteArray; 
float *floatArray; 

// Adding byte data 
byteArray = (Byte[]){254,1,200}; 
[data appendBytes:byteArray length:3*sizeof(Byte)]; // Adds 254, 1, 200 

// Adding floating point data – Hopefully the receiver has the same floating point format. 
floatArray = (float[]){0.5}; 
[data appendBytes:floatArray length:1*sizeof(float)]; // Adds 4! bytes representing the float value 

// Adding string data – Hopefully the receiver uses the same string encoding 
[data appendData:stringData]; // Adds the bytes for the string in the above encoding. 
+0

은 주셔서 감사합니다 대답. 시험 할 시간을주세요. – SRI

+0

Safari에 입력 했으므로 일부 오타가있을 수 있습니다. C에서 포인터, 배열 및 바이너리 데이터가 어떻게 작동하는지 이해해야합니다. 이는 단지 예일뿐입니다. –