How to convert unsigned char to NSString in iOS - iphone

Can anyone tell me how to convert an unsigned char to an NSString?
Here's the code I am using, but for some reason if I try to do anything with the NSString, like set a UITextView text, it gives me an error. The NSLog works correctly though. Thanks in advance.
- (void)onTagReceived:(unsigned char *)tag
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *myTag = [NSString stringWithFormat:#"%02x%02x%02x%02x%02x\n",tag[0],tag[1],tag[2],tag[3],tag[4]];
NSLog(#"currentTag: %#",myTag);
[displayTxt setText:myTag];
[pool release];
}

If tag is a C string (null-terminated, that is), then you can use [NSString stringWithUTF8String:(char *)tag]. If you want the hex values, then your code using %02x is fine.

#jtbandes: you are correct. The other way you can do this:
NSString *str = [NSString stringWithCString:tag length:strlen(tag)];

Related

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>

EXC_BAD_ACCESS when using string declared in header file

I've declared a string in my header file like so:
#property (nonatomic, retain) NSString *resultOfHash;
I call my getHash method like so:
NSString *hash = [self getHash];
My getHash method is:
-(NSString *) getHash
{
//Get username form Keychain
KeychainItemWrapper *keyChain = [[KeychainItemWrapper alloc] initWithIdentifier:KeyChainName accessGroup:nil];
username = [keyChain objectForKey:(__bridge id)kSecAttrAccount];
//get token from NSUserDefauls
NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:#"Token"];
NSString *toHash = [[username stringByAppendingString:HashExtra] stringByAppendingString:token];
const char *s = [toHash cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
CC_SHA512(keyData.bytes, keyData.length, digest);
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
//convert to string
resultOfHash = [out description];
//App crashed out above
// get rid of unwanted characters
resultOfHash = [resultOfHash stringByReplacingOccurrencesOfString:#" " withString:#""];
resultOfHash = [resultOfHash stringByReplacingOccurrencesOfString:#"<" withString:#""];
resultOfHash = [resultOfHash stringByReplacingOccurrencesOfString:#">" withString:#""];
//log to make sure it works
NSLog(#"hash is: %#", resultOfHash);
return resultOfHash;
}
My code crashes out at the line: ResultOfHash = [out description]; but I'm not sure why.
When I use a local variable the conversion works fine but then I cannot return the local variable from the getHash method. Example:
Replace ResultOfHash = [out description];
with
NSString *local = [out description];
return local;
and the conversion works fine and when I debug line by line, the debugger will go to my closing bracket on my method and then produce the EXC_BAD_ACCESS error.
I've tried running NSZombie but that didn't find anything at all.
Any help in trying to sort this out would be greatly appreciated.
Have a look at the answer in this question. Try converting to NSString using
[NSString *local = [[[NSString alloc] initWithData:out encoding:NSASCIIStringEncoding];
I haven't tested this code with this encoding, but it's similar to something I already use.
Update -
I corrected an error in the code above. I somehow left the method signiture out in a distracted copy and paste.
I think the problem is here:
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
CC_SHA512(keyData.bytes, keyData.length, digest);
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
You are using CC_SHA512, but only allocate array of size CC_SHA1_DIGEST_LENGTH, which is smaller and will lead to the buffer overrunning.
To correct this, you should use CC_SHA512_DIGEST_LENGTH instead.
It's crashing because out is unretained. You should add retain:
resultOfHash = [[out description] retain];
or use retained property:
self.resultOfHash = [out description];
Check this, it should be work.
You probably need to use an NSMutableString.

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];

Is there a way for NSString to display HTML character codes?

I have an NSString that has the following value:
"What#39;s up fellas!"
Is there a simple way to turn HTML char codes like #39; (equivalent to ') into an apostrophe etc?
check GTMNSString+HTML.h out :) It's a part of the Google Toolbox, an extension for iOS development.
taken from this question
Try this one, it works:
#import "NSString+HTML.h"
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *r = #"This is a '\'";
NSString *s = #"This is a &ltHTML-Tag&gt";
NSString *encodedstring = [r kv_encodeHTMLCharacterEntities];
NSString *decodedstring = [s kv_decodeHTMLCharacterEntities];
}
NSString has an UTF8 encode-decode function:
- (id)initWithUTF8String:(const char *)bytes
+ (id)stringWithUTF8String:(const char *)bytes
- (const char *)UTF8String
See the Class Reference here