NSData bytes to string - iphone

I get NSData of bytes that look like this:
2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d353731 35343039 37373139
34383437 34303832 30333533 30383232 380d0a43 6f6e7465 6e742d44 6973706f 73697469 6f6e3a20
666f726d 2d646174 613b206e 616d653d 2266696c 65223b20 66696c65 6e616d65
3d224265 61636820 426f7973 202d2047 6f6f6420 56696272 6174696f 6e732e6d
and i want to convert it to NSString, i tried this method but it give me a nil to the string:
NSString* postInfo = [[NSString alloc] initWithBytes:[postDataChunk bytes] length:[postDataChunk length] encoding:NSUTF8StringEncoding];

You can use,
NSString* newStr = [[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding];
If the data is null-terminated, you should instead use
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
for further reference see these links:
Convert UTF-8 encoded NSData to NSString
NSString class reference
http://homepage.mac.com/mnishikata/objective-c_memo/convert_nsdata_to_nsstring_.html

If you're looking to trace the actual hex values of the NSData object, I use this approach:
uint8_t *bytes = (uint8_t*)myNSDataObject.bytes;
NSMutableString *bytesStr= [NSMutableString stringWithCapacity:sizeof(bytes)*2];
for(int i=0;i<sizeof(bytes);i++){
NSString *resultString =[NSString stringWithFormat:#"%02lx",(unsigned long)bytes[i]];
[bytesStr appendString:resultString];
}

Related

Conversion of Hex octets to Unicode

NSString* code = #"\x03\x7e";
const char *cString = [code cStringUsingEncoding:NSUnicodeStringEncoding];
NSData* unicodeData = [NSData dataWithBytes:cString length:strlen(cString)];
NSString* convertedString = [[NSString alloc] initWithData:unicodeData encoding:NSUnicodeStringEncoding];
I’d like the convertedString to be the unicode value of \x03\x7e which is a greek question mark (looks kind of like a semicolon). My converted string ends up just as an empty string…
Any idea how I can do this?
Thanks!
Sample Code:
NSString *code = #"\x03\x7e";
NSData *data = [code dataUsingEncoding:NSUnicodeStringEncoding];
NSString *codeNew = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];

Converting UTF8 Hex string to regular UTF8 encoded NSString

I am getting UTF-8 (hex): Hc3b8rt back from a server instead of the string "Hørt".
I need to convert this response to regular UTF-8.
What I have tried:
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string UTF8String];
NSString *str = [NSString stringWithUTF8String:cfilename];
Thank you for your time!
There's no way you can decode this. As #JoachimIsaksson stated in the comments above, how can you tell if "abba" is exactly "abba" or two unicode chars?
use string encoding, NSISOLatin1StringEncoding
- (id)initWithCString:(const char *)nullTerminatedCString
encoding:(NSStringEncoding)encoding
Or shortly,
NSString *str = [NSString stringWithCString:cfilename
encoding:NSISOLatin1StringEncoding];
Edit after comments:
This is kind of strange. I have done some experiments after your comments and found some strange behaviour.
- (void) testStringEncodingOK {
NSString *string = #"h\u00c3\u00a5r";
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
This output: hår
But if you get the \U in capital, not \u, then I replaced them to \u. And then it did not work. Seem the ,
- (void) testStringEncodingConfused {
NSString *string = #"h\\U00c3\\U00a5r";
string = [string stringByReplacingOccurrencesOfString:#"\\U" withString:#"\\u"];
NSLog(#"Original string:%#", string); // now string = #"h\u00c3\u00a5r"
const char *cfilename=[string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *cs = [NSString stringWithUTF8String:cfilename];
NSLog(#"String: %#", cs);
}
The output is, h\u00c3\u00a5r
Use below code..
const char *ch = [yourstring cStringUsingEncoding:NSISOLatin1StringEncoding];
 yourstring = [[NSString alloc]initWithCString:ch encoding:NSUTF8StringEncoding];
NSLog(#"%#",yourstring);
let me know it is working or not...
Happy Coding....
use this code
NSString *string = [dict objectForKey:#"suggest"];
const char *cfilename=[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *str = [NSString stringWithUTF8String:cfilename];
and tell if it is working or not.

how to encode a UInt32 scalar type into a NSData object

I am currently creating this NSData object. I would like to put in sever different objects that are of type NSString and UInt32. I know how to put a NSString into my NSData object, but I don't know how to do this with a UInt32 scalar type.
this is how I do it with a NSString
- (void) constructRequest
{
NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
UInt32 protocolInt = [self addProtocolVersion];
NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:#"/Users/imac/Desktop/_dataDump.dat" atomically:YES];
}
So I have figured it out, and instead of just updating my question I will put in the answer so others can see that this question has been answered if they are looking to do something similar.
code is as follows
- (void) constructRequest
{
//NSString *mystring = [[NSString alloc] initWithString:[self addMethodName]];
UInt32 protocolInt = [self addProt];
NSData * data = [[NSData alloc] initWithBytes:&protocolInt length:sizeof(protocolInt)];
//NSData* data=[mystring dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:#"/Users/imac/Desktop/_dataDump.dat" atomically:YES];
}
Does it need to be NSData? You could use NSString or NSNumber (both can be saved in a property list).
Your scheme doesn't really distinguish between a 4-byte string and a UInt32, if that matters.
You can use htonl(),htons(), ntohl() and ntohs() to make it endian-safe.
htonl()--"Host to Network Long int" 32Bytes
ntohl()--"Network to Host Long int" 32Bytes
htons()--"Host to Network Short int" 16Bytes
ntohs()--"Network to Host Short int" 16Bytes
Example:
- (void)testExample {
UInt32 length = 0x1a2b3c4d;
NSLog(#"%x", length);
length = htonl(length);
NSLog(#"%x", length);
NSMutableData *data = [[NSMutableData alloc] init];
[data appendBytes:&length length:4];
NSLog(#"%#", data);
}
print:
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] 1a2b3c4d
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] 4d3c2b1a
2015-10-29 15:46:49.224 UPHTTP-iOS[3896:101301] <1a2b3c4d>

Converting a uint8_t array to an NSString

How can I affect a uint8_t array (see decryptedBuffer below) to an NSString?
uint8_t *decryptedBuffer;
NSString *cle2=[NSString stringWithUTF8String:decryptedBuffer];
NSString *str2=[player.name AES256DecryptWithKey:cle2];
NSLog(str2);
free(plainBuffer);
free(cipherBuffer);
free(decryptedBuffer);
uint8_t * is just a byte string which is compatible with char *, so you should just be able to pass the casted pointer to stringWithUTF8String, assuming the decrypted string is UTF-8 and it is NULL terminated:
NSString *s = [NSString stringWithUTF8String:(char *)decryptedBuffer];
If the data is not NULL terminated, you can use this:
NSString *s = [[[NSString alloc] initWithBytes:decryptedBuffer
length:length_of_buffer
encoding:NSUTF8StringEncoding] autorelease];
decryptedBuffer is an int (uint8_t), NSString stringWithUTF8String only works on strings, not ints. I think I found what you need: http://lists.apple.com/archives/cocoa-dev/2004/Apr/msg01437.html
That person used this syntax:
NSString *theDigitsIWant = [[NSNumber numberWithInt:x] stringValue];
So you should do this:
NSString *cle2 = [[NSNumber numberWithInt:decryptedBuffer] stringValue];

NSString to NSData conversion Problem

I have some Bytes of image in my string and i want to draw it to UIImageView ...Here is my code
NSString* str= #"<89504e47 0d0a1a0a 0000000d 49484452 ........... 454e44ae 426082>";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"My NSDATA %#",data);
imageView.image=[UIImage imageWithData:data];
Now when i saw that printed data on console it is not in same format what i gave to that string..The output is something like.....
<3c383935 30346534 37203064 30613161..........
So my imageview show nothing..... please help
if question was: How to convert string data to image then this is answer.
NSData *imgData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"icon" ofType:#"png"]];
// set your string data into inputString var
NSString *inputString = [imgData description];
NSLog(#"input string %#",inputString);
// clearing string from trashes
NSString *dataStr = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
// separate by words of 4 bytes
NSArray *words = [dataStr componentsSeparatedByString:#" "];
// calculate number of bytes
NSArray *sizes = [words valueForKey:#"length"];
int sizeOfBytes = 0;
for (NSNumber *size in sizes) {
sizeOfBytes += [size intValue]/2;
}
int bytes[sizeOfBytes];
int counts = 0;
for (NSString *word in words) {
// convert each word from string to int
NSMutableString *ostr = [NSMutableString stringWithCapacity:[word length]];
while ([word length] > 0) {
[ostr appendFormat:#"%#", [word substringFromIndex:[word length] - 2]];
word = [word substringToIndex:[word length] - 2];
}
NSScanner *scaner = [NSScanner scannerWithString:ostr];
unsigned int val;
[scaner scanHexInt:&val];
bytes[counts] = val;
counts++;
}
// get NSData form c array
NSData* data = [NSData dataWithBytes:bytes length:sizeOfBytes];
NSLog(#"My NSDATA %#",data);
// your image is ready
UIImage *image = [UIImage imageWithData:data];
NSLog(#"image: %#",image);
what you are seeing in NSLog output are the ASCII codes of the string characters.
for example:
NSString* str = #"A";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
you will see something like:
<41....
that's because 0x41 is the code for letter A.
Same is happening with your string.
The data is exactly what you're feeding it: a simple string (printed as raw byte values). But I guess your input string is a hexdump and you manually need to turn into bytes.