I am working on my first iPhone application, in that application I have to calculate the length of NSString, I have tried the available methods and solutions here on SO but for the length is always wrong. For example for a string "test4" NSString.length returns 12 while it should return 5.
I have tried NSString's length property and lengthOfBytesUsingEncoding but both return the same result.
Any help would be appreciated.
EDIT
NSString *string = #"test4";
[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; // returns 12
string.length; // returns 12
Complete Code
+(NSString *)AES256Encrypt:(NSString *)data withKey:(NSString *)rawkey{
rawkey = [NSString stringWithFormat:#"%#%#", #"123456789023456", rawkey];
rawkey = [rawkey substringWithRange:NSMakeRange(0, 32)];
NSData *key = [rawkey dataUsingEncoding:NSUTF8StringEncoding];
NSData *iv = [key subdataWithRange:NSMakeRange(0, 16)];
const char *bytes = [data cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%d", data.length); // prints 12
data = [self encode:bytes length:data.length];
NSData *rawData = [data dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus status = kCCSuccess;
NSData *encrypted = [rawData dataEncryptedUsingAlgorithm:kCCAlgorithmAES128 key:key initializationVector:iv options:kCCOptionPKCS7Padding error:&status];
NSString *text = [encrypted base64EncodedString];
return text;
}
Thanks
NSString *myString = #"test4";
int i =myString.length;
NSLog(#"Count =%d",i);
which print Count = 5
Related
I have an one hexa decimal number
535443326663315634524877795678586b536854535530342f44526a795744716133353942704359697a6b736e446953677171555473
I want to convert this number to ASCII format which will look like this
STC2fc1V4RHwyVxXkShTSU04/DRjyWDqa359BpCYizksnDiSgqqUTsYUOcHKHNMJOdqR1/TQywpD9a9xhri
i have seen solutions here but none of them is useful to me
NSString containing hex convert to ascii equivalent
i checked here but they give different result. Any help
This works perfectly
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%c", decimalValue];
NSLog(#"string--%#",string);
}
_hexString1=string;
NSLog(#"string ---%#",_hexString1);
return string;
}
If you're starting with NSData * you could get the ASCII string this way:
NSData *someData = [NSData dataWithHexString:#"ABC123"];
NSString *asciiString = [[NSString alloc] initWithData: someData encoding:NSASCIIStringEncoding];
I'm new to iPhone development, I want to convert a string to hex format.
For example 00A400024F01 to 0x00,0xA4,0x00,0x02,0x4F,0x01 I guess I should start by dividing the string and then convert the grouped value. I don't know how to do that.
u just found answer from this stackoverflow question:-
How to convert an NSString to hex values
+ (NSString *) stringToHex:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
// [hexString [NSString stringWithFormat:#"%02x", chars[i]]]; /*previous input*/
[hexString appendFormat:#"%02x", chars[i]]; /*EDITED PER COMMENT BELOW*/
}
free(chars);
return [hexString autorelease];
}
UPDATE
You can divide one sting on to two string using below method:-
NSString * mystring = #"Hello,How are you";// suppos your string like that
NSArray * array = [mystring componentsSeparatedByString:#","];
NSString * str1 = [array objectAtIndex:0]; //Hello
NSString * str2 = [array objectAtIndex:1]; //How are you
and if you want to murge two string in to one string like :-
NSString *str1=#"hi Sweet Lady";
NSString *str2=#"How are you";
NSString *mainstr=[NSString stringWithFormat:#"%# %#",str1,str2];
Output is ==== hi Sweet Lady How are you
I'm using the NSData+compression.h and the Base64Transcoder.h elements to be able to zip and unzip content.
Basically to unzip the server responses.
The unzip method works perfectly
+ (NSString *) unzip: (NSString*) stringValue{
Byte inputData[[stringValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[[stringValue dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];
size_t inputDataSize = (size_t)[stringValue length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
//And now we gunzip:
NSData* result = [theData gzipInflate];//make bigger==gunzip
NSString *temp = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return temp;
}
But when I try to zip a content, using the simetric way, the gzipDeflate fails, and return an empty or nil value.
This is my zip code
+ (NSData *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
Byte inputData[[result length]];
[result getBytes:inputData];
size_t inputDataSize = (size_t)[result length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);
char outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64EncodeData(inputData, inputDataSize, outputData, &outputDataSize, NO);
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];
return theData;
}
Any suggestions?
Thanks
The problem was on the Base64 encoder.
+ (NSString *) zip:(NSData *) theSourceData {
// And now we zip:
NSData *result = [theSourceData gzipDeflate];
NSString *source = [NSString base64StringFromData:result length:[result length]];
return source;
}
We've integrated the base64StringFromData:length: method to solve it.
Thanks,
Ivan
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].
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.