How to convert HEX to NSString in Objective-C j? - ios

I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?

- (NSMutableString *) hextostring:(NSString *) str{
//ت
NSMutableString *string = [[NSMutableString alloc]init];
str = [str stringByReplacingOccurrencesOfString:#"&#" withString:#"0"];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"z;"];
NSArray *arr = [str componentsSeparatedByString:#";"];
for (int i =0; i<[arr count]; i++) {
if ([[arr objectAtIndex:i] isEqualToString:#"z"]) {
[string appendString:#" "];
} else {
unsigned x;
[[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
[string appendFormat:#"%C",(unichar)x];
}
}
NSLog(#"%#",string);
return string;
}

Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
NSString *nospaces = [raw stringByReplacingOccurrencesOfString:#" " withString:#""]; // one way to remove the spaces
const char *cString = [nospaces UTF8String]; // C string
NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
NSString *decoded = attributed.string; // and finally as plain text
return decoded;
}
That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = #"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(#"%# -> %#", raw, decoded);
HTH

Related

How to remove 08 hexadecimal character from an NSString

I have a long string, and I would like to remove a specific hexadecimal character from it.
NSString * myString = #"longlongstringwithcharacters\"ofallsorts\"";
Any suggestions?
The hex character I am after is 08, that corresponds to backspace. How can I use code like the following to substitute it? I have no idea on how to represent 08 in a string:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:#" " withString:#""];
EDIT:
I will try to clarify a bit more what I am trying to do..
I am trying to remove all occurrences of a character that corresponds to 08 hex from the string that I receive as payload.
The payload is in a string format and I found out the character by using Xcode debugger and view the hex codes of the string as there was an invalid character when trying to covert the NSData corresponding to the string to a NSDictionary.
I am not sure how to phrase the problem correctly..
- (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];
}
return string;
}
Try this code...This will help you to convert Hex to string
NSString * str = #"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:#"%c", (char)value];
i+=2;
}
this will help u to convert Hex to NSString
This code worked for me:
NSString * dataString = message.payloadString;
NSString * wrongCharacter = [[NSString alloc] initWithFormat:#"%c", (char)0x08];
dataString = [dataString stringByReplacingOccurrencesOfString:wrongCharacter withString:#""];

correctly convert hex to base64

I'm trying to get the correct base64 string by encoding a hex string. It works when I use converter websited but my App does not.
NSData* sentData = [combinedHexMessage dataUsingEncoding : NSUTF8StringEncoding];
NSLog (#"%#",sentData);
NSData* sentDataBase64 = [sentData base64EncodedDataWithOptions:0];
NSLog(#"%#",[NSString stringWithUTF8String:[sentDataBase64 bytes]]);
This is my code. combinedHexMessage looks like this in NSLog:
ffd8ffe000104a46494600010101006000600000ffdb004300020101020101020 ...
sentData :
66666438 66666530 30303130 34613436 34393436 30303031 30313031 ...
sentDataBase64 :
ZmZkOGZmZTAwMDEwNGE0NjQ5NDYwMDAxMDEwMTAwNjAwMDYwMDAwMGZmZGIwMDQzM ...
But it should look like:
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFB ...
Because this is the string I get after I paste my hex string there:
http://tomeko.net/online_tools/hex_to_base64.php?lang=en
What am I doing wrong?
If you have a hex string that represents an image, you simply want to convert that hex string to a NSData
NSString *hexadecimalString = ...
NSData *data = [hexadecimalString dataFromHexadecimalString];
self.imageView.image = [UIImage imageWithData:data];
Where dataFromHexadecimalString might be defined in a NSString category like so:
#implementation NSString (Hexadecimal)
- (NSData *)dataFromHexadecimalString
{
// in case the hexadecimal string is from `NSData` description method (or `stringWithFormat`), eliminate
// any spaces, `<` or `>` characters
NSString *hexadecimalString = [self stringByReplacingOccurrencesOfString:#"[ <>]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [self length])];
NSMutableData * data = [NSMutableData dataWithCapacity:[hexadecimalString length] / 2];
for (NSInteger i = 0; i < [hexadecimalString length]; i += 2) {
NSString *hexChar = [hexadecimalString substringWithRange: NSMakeRange(i, 2)];
int value;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
uint8_t byte = value;
[data appendBytes:&byte length:1];
}
return data;
}
#end
No base-64 conversion is needed in this process.

How to replace special characters in NSString with unknown index

I am trying to replace some characters with unknown index like this(i need to replace this Ă,Ŏ,Ĭ,ă,ŏ,ĭ and my input nsstring can be anything):
(void)repairText:(NSString *)textToRepair{`
NSString *pom = textToRepair;`
int pomNum = [pom length];
NSLog(#"Input nsstring: %#",pom);
for (int a = 0; a<pomNum; a++) {
NSString *pomChar, *pomChar2;
pomChar = [pom substringFromIndex:a];
pomChar2 = [pomChar substringToIndex:(1)];
NSLog(#"Char to repair: %#",pomChar2);
if ([pomChar2 isEqual: #"Ă"] || [pomChar2 isEqual:#"Ŏ"] || [pomChar2 isEqual:#"Ĭ"] || [pomChar2 isEqual:#"ă"] || [pomChar2 isEqual:#"ŏ"] || [pomChar2 isEqual:#"ĭ"]) {
if ([pomChar2 isEqual:#"Ă"]) {
NSLog(#"Wrong big a");
}
if ([pomChar2 isEqual:#"Ŏ"]) {
NSLog(#"Wrong big o");
}
if ([pomChar2 isEqual:#"Ĭ"]) {
NSLog(#"Wrong big i");
}
if ([pomChar2 isEqual:#"ă"]) {
NSLog(#"Wrong small a");
}
if ([pomChar2 isEqual:#"ŏ"]) {
NSLog(#"Wrong small o");
}
if ([pomChar2 isEqual:#"ĭ"]) {
NSLog(#"Wrong small i");
}
} else {
NSLog(#"Good");
}
}
pom = [textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#" kulka "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#" jen "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#" libra "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#" euro "];
[self synthesize:pom];
}
But I am having trouble with 'if'. If anyone know about this, please help in this regard.
NSString *str=#"ĂdsdaĬsd";
str=[str stringByReplacingOccurrencesOfString:#"Ă" withString:#""];
str=[str stringByReplacingOccurrencesOfString:#"Ĭ" withString:#""];
NSLog(#"%#",str);
O/p :dsdasd
NSString has functions to do that for you. dataUsingEncoding:allowLossyConversion: is the method you need.
From the documentation:
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.
Sample code:
NSString *str = #"á, é, í, ó, ú, ü, ñ";
NSData *asciiStringData = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *finalString = [[NSString alloc] initWithData:asciiStringData
encoding:NSASCIIStringEncoding];
The final string will be : a, e, i, o, u, u, n
NSString * textToRepair = #"Your String";
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#"kulka"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#"jen"]
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#"libra"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#"euro"];;
and now textToRepair is your output string with changes.
You can used this:
NSString * myString = #"Hello,";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%#xx",newString);
I hope this is used full to you.

Shuffling a greek word in iOS prints unknown symbols

I want to shuffle a string that contains Greek characters:
Here is my code:
- (void)shuffle {
NSLog(#"Will shuffle :%#",anagram2);
NSData* data = [anagram2 dataUsingEncoding:NSWindowsCP1253StringEncoding];
NSLog(#"after encoding :%#",anagram2);
NSString *someString = [[NSString alloc]initWithData:data encoding:NSWindowsCP1253StringEncoding];
NSLog(#"Greek word:%#",someString);
int length = anagram2.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
NSLog(#"Character:%#",letter);
[letters addObject:someLetter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
//NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
}
I can see the Greek word correctly. But the shuffling does not work. How can I extract each character and add it to a letters array. It works with English words but not with Greek ones, so I suppose that I should replace this:
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
with something else.
The main problem seems to me that
[NSString stringWithFormat:#"%c":...]
works only with ASCII characters. You would have to use at least the "%C" format to make
it work with Unicode characters.
Also the conversion from NSString to NSData and back would fail as soon as you have any characters that are not available in the specified encoding.
The following method avoids all these problems and should work with arbitrary Unicode characters
(even with Emojis, which are internally represented as 2 UTF-16 characters):
NSString *string = #"Ελλάδα 😄";
NSLog(#"Will shuffle: %#", string);
// Convert string to an array of (32 bit) Unicode characters:
NSMutableData *data = [[string dataUsingEncoding:NSUTF32BigEndianStringEncoding] mutableCopy];
uint32_t *letters = [data mutableBytes];
int length = [data length]/4; // The number of 32-bit Unicode characters
// Shuffle the Unicode characters:
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
uint32_t tmp = letters[i];
letters[i] = letters[value];
letters[value] = tmp;
}
// Create new string from the shuffled Unicode characters:
NSString *shuffled = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding];
NSLog(#"Shuffled: %#", shuffled);
Output:
Will shuffle: Ελλάδα 😄
Shuffled: α😄άλλ Εδ

How convert string utf-8?

i've an NSString like this:
NSString *word = #"119,111,114,100"
So, what i want to do is to convert this NSString to word
So the question is, in which way can i convert a string to a word?
// I have added some values to your sample input :-)
NSString *word = #"119,111,114,100,32,240,159,145,141";
// Separate components into array:
NSArray *array = [word componentsSeparatedByString:#","];
// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
bytes[i] = [array[i] intValue];
}
// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
Output:
word 👍
Try this:
NSString *word = #"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:#","];
for (NSString *string in array) {
char character=[string integerValue];
NSLog(#"%c",character);
}
Output:
w
o
r
d
libicu it's an UTF8 library that supports a conversion from an array of bytes as stated here.
The thing is, it offers Java, C or C++ APIs, not obj-c.

Resources