Convert a hash to NSString? - iphone

Using the Evernote API, I have an object which has an NSUInteger property called hash. For the specific object I'm looking at, this is equal to:
<f5b5444b 33e740b7 f9d49a3b ddb6a39c>
I want to convert this into an NSString. Doing this:
[NSString stringWithFormat:#"%d", noteResource.hash]
Gives me this:
530049088
How could I correctly convert the hash value to an NSString?

When you see something output as "<" 8 hex digits space .... ">", it's the result of logging a NSData object (NSLog(#"%#", myDataObject);). So I believe what you have is not an NSUInteger, but a NSData * object.
There is no built in method to convert between strings and data, you need to do it in code:
- (NSString *)dataToString:(NSData *)data
{
NSUInteger len = [data length];
NSMutableString *str = [NSMutableString stringWithCapacity:len*2];
const uint8_t *bptr = [data bytes];
while(len--) [str appendFormat:#"%02.2x", *bptr++];
return str;
}
If this works, you can write your own stringToData method reversing the above, if needed.

Related

Converting NSString, data type expression, to actual NSData

NSString *string1 = #"<616263>";
I want to make this into NSData *data1 = <616263>;
so that when I
NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", string2);
Result: abc
would come out
p.s.
<616263>, this is data expression of #"abc"
The trick is converting 616263 to abc. Since you are starting with the ASCII representation of the character codes, you need to convert your NSString to an array of bytes (or your original data source to an array instead of saving it as an NSString in the first place).
NSString *string1 = #"616263";
// Make sure that buffer is big enough!
char sourceChars[7];
[string1 getCString:sourceChars maxLength:7 encoding:NSUTF8StringEncoding];
char destBuffer[3];
char charBuffer[3];
// Loop through sourceChars and convert the ASCII character groups to char's
// NOTE: I assume that these are always two character groupings per your example!
for (int index = 0; index < [string1 length]; index = index + 2) {
// Copy the next two digits into charBuffer
strncpy(charBuffer, &sourceChars[index], 2);
charBuffer[2] = '\0';
// convert charBuffer (ie 61) from hex to decimal
destBuffer[index / 2] = strtol(charBuffer, NULL, 16);
}
// destBuffer is properly formatted: init data1 with it.
NSData *data1 = [NSData dataWithBytes:destBuffer length:[string1 length]/2];
// Test
NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", string2); // Prints abc

NSMutableArray to byte array to string

I have an iPad app which communicates with a webservice. There I can download an encrypted file. In a particular request I get a json with login credentials. Also in that json is a key which is used to encrypt the data.
The key looks like:
[0,44,215,1,215,88,94,150]
With the json framework I can put this key into an NSMutableArray. After that I use a AES256 code to decrypt the file. But that code needs a NSString as a key. So my question is: how can I decode that NSMutableArray into an NSString? I guess I first need to put it into an byte arary, and then put it into an NSString?
Who can help me with this one?
Thanks in advance!
Firstly, convert your array of numbers (I assume they're given as NSNumbers) into a C array using code similar to the first snippet in the accepted answer here. In other words, something similar to this:
// Test array for now -- this data will come from JSON response
NSArray* nsArray = [NSArray arrayWithObjects:[NSNumber numberWithChar:1],
[NSNumber numberWithChar:2],
nil];
char cArray[2];
// Fill C-array with ints
int count = [nsArray count];
for (int i = 0; i < count; ++i) {
cArray[i] = [[nsArray objectAtIndex:i] charValue];
}
Then create an NSString using the correct encoding:
NSString *encodedStr = [NSString stringWithCString:cArray encoding:NSUTF8StringEncoding];
Note: these are code sketches, they haven't been tested!
EDIT: changed from ints to chars.
If your array is the sequence of numbers, you can loop through it
//Assume you have created keyArray from your JSON
NSMutableString * keyString = [NSMutableString string];
for (id element in keyArray) {
[string appendFormat:#"%#", id];
}
// if you need the comma's in the string
NSMutableString * keyString = [NSMutableString string];
for (id element in keyArray) {
[string appendFormat:#"%#,", id];
}
int length = [string length];
NSRange range = NSMakeRange(0, length-1);
string = [string substringWithRange:range];

Converting hex string to hex data

I currently have an NSString containing hex values. I need to convert this NSString object into an NSData object, without changing its contents at all.
I use this code to "parse" the debug output of an NSData object (what you get in the console if you just NSLog an NSData object) back into NSData:
-(NSData*) bytesFromHexString:(NSString *)aString;
{
NSString *theString = [[aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:nil];
NSMutableData* data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= theString.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [theString substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
if ([scanner scanHexInt:&intValue])
[data appendBytes:&intValue length:1];
}
return data;
}
It's not my most robust code, but it does the job of parsing [nsdata_object description].

Help with NSString of int's to NSString of ASCII characters?

I have implemented some code to convert a NSString of "text" to an NSString of (ASCII) ints, like so:
#"Hello" is converted to #"72 101 108 108 111"
However, I am having quite a bit of difficulty doing the opposite. Starting with a string of ints (with the spaces) and converting back to the plain string of text.
What I need: #"72 101 108 108 111" must be converted to #"Hello"
I have tried breaking up the input string into an int array, iterating through it, and using repeatedly the following:
[NSString stringWithFormat:#"%c", decCharArray[i]]
However, the problem with that is that it parses each particular digit into ASCII, converting the 7, the 2, the space, the 1, etc.
Thanks a ton in advance.
Sounds like you have the right approach. Try using [string componentsSeparatedByString:#" "] to split the string at the spaces. Then you can convert each of those to numbers, and back into strings.
There is no real magic on it. Since you'll be using ASCII, to convert an int
to a char all you have to do is an assignment, as you may already know:
char a = 65; /* a contains 'A' */
NSString has a very convenient method componentsSeparatedByString: that will
return an array of strings containing your numbers, and you can get an int
from a string with the intValue method. Thus, all you have to do is to split
the string and iterate through the components assigning their int value to a
char array. Here is an example function that does that:
NSString *
TextFromAsciiCodesString (NSString *string)
{
NSArray *components = [string componentsSeparatedByString:#" "];
NSUInteger len = [components count];
char new_str[len+1];
int i;
for (i = 0; i < len; ++i)
new_str[i] = [[components objectAtIndex:i] intValue];
new_str[i] = '\0';
return [NSString stringWithCString:new_str
encoding:NSASCIIStringEncoding];
}
And a simple use of it, with your "Hello" example:
NSString *string = #"72 101 108 108 111";
NSLog(#"%#", TextFromAsciiCodesString(string));
Actually, it's a bit different as your example was "Hell^K" :-)
You can also trying using NSString's enumerateSubstringsInRange:options:usingBlock:.
Usage
NSString * hello = #"72 101 108 108 111";
NSMutableString * result = [NSMutableString string];
[hello enumerateSubstringsInRange:NSMakeRange(0, [data length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[result appendString:[NSString stringWithFormat:#"%c", [substring intValue]]];
}];
NSLog(#"%#", result);

how can i use the UTF8string for the NSArray

I have taken char data into database into array. now i want to convert that data into string.
how can i convert array data into NSString.
If you have a const char * instance, you can use the NSString method + stringWithCString:encoding:. For example:
NSString *_myString = [NSString stringWithCString:_myCharPtr encoding:NSUTF8StringEncoding];
To put that into an NSArray*, you might do the following:
NSArray *_myArray = [NSArray arrayWithObjects:_myString,nil];
use
[NSString stringWithUTF8String:<#(const char *)nullTerminatedCString#>]