Conversion of Hex octets to Unicode - iphone

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

Related

NSString unichar from int

I have an int value which I obtained from the character 爸, which is 29240. I can convert this number to hex, but I have no clue how to write the chinese character out in an NSString with only the int 29240.
Basically, what I did was:
NSString * s = #"爸";
int a = [s characterAtIndex:0];
NSLog(#"%d", a);
What it gave as output was 29240.
However, I don't know how to create an NSString that just contains 爸 from only the int 29240.
I converted 29240 into binary which gave me 7238, but I can't seem to create a method which allows me to input any integer and NSLog the corresponding character.
I can hard code it in, so that I have
char cString[] = "\u7238";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
But I'm not sure how to do it with any int.
Thanks to anyone who can help me!
To create a string from one (or more) Unicode characters use initWithCharacters:
unichar c = 29240;
NSString *string = [[NSString alloc] initWithCharacters:&c length:1];
NSString uses UTF-16 characters internally, so
this works for all characters in the "Basic Multilingual Plane", i.e. all characters up to U+FFFF. The following code works for arbitrary characters:
uint32_t ch = 0x1F60E;
ch = OSSwapHostToLittleInt32(ch); // To make it byte-order safe
NSString *s1 = [[NSString alloc] initWithBytes:&ch length:4 encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", s1);
// Output: 😎
Try out this code snippet to get you started in the right direction:
NSString *s = #"0123456789";
for (int i = 0; i < [s length]; i++) {
NSLog(#"Value: %d", [s characterAtIndex:i]);
}
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];

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.

NSData bytes to string

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

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.

NSData to NString conversion problem

I'm getting an HTML file as NSData and need to extract some parts of it. For that I need to convert it to NSString with UTF8 encoding. The thing is that this conversion fails, probably because the NSData contains bytes that are invalid for UTF8. I have tried to get the byte array of the data and go over it, but each time I come across non ASCII character (hebrew letters for example) I get jibrish.
Help will be appreciated.
UPDATE:
To Gordon - the NSData generated like that:
NSData *theData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
When I say that the conversion fails I mean that
[[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding]
returns nil
To Ed - Here is my code (I got the Byte array from NSData, found what I need, and constructed another Byte array from that - turned it to NSData and then attempted to convert it to NSString... sounds kinda complicated...)
-(NSString *)UTF8StringFromData:(NSData *)theData{
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
NSLog(#"%d %d",begin1, end1);
int j = 0;
for (int i = begin1; i < end1; i++){
arr1[j] = arr[i];
j++;
}
arr1[j]='\0';
NSData *temp = [NSData dataWithBytes:arr1 length:j];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
I know this is an old topic but it came up when I was looking for the solution today. I've solved it now so I'm just posting it for others who might run into this page looking for a solution.
Here's what I do in an asynchronous request:
I first store the text encoding name in connection:didReceiveResponse using
encodingName = [[NSString alloc] initWithString:[response textEncodingName]];
Then later in my connectionDidFinishLoading method I used
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef) encodingName));
NSString *payloadAsString = [[NSString alloc] initWithData:receivedData encoding:encoding];
To Gordon - the NSData generated like that:
NSData *theData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
When I say that the conversion fails I mean that
[[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding]
returns nil
To Ed - Here is my code (I got the Byte array from NSData, found what I need, and constructed another Byte array from that - turned it to NSData and then attempted to convert it to NSString... sounds kinda complicated...)
-(NSString *)UTF8StringFromData:(NSData *)theData{
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
NSLog(#"%d %d",begin1, end1);
int j = 0;
for (int i = begin1; i < end1; i++){
arr1[j] = arr[i];
j++;
}
arr1[j]='\0';
NSData *temp = [NSData dataWithBytes:arr1 length:j];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
have you checked the charset= in the HTTP headers and/or the document itself? The most likely reason for the conversion to fail is because the bytes don't represent a valid UTF-8 string.
I'm not sure if you're aware, you don't really need to copy the array to another array before putting it into the new NSData object.
-(NSString *)UTF8StringFromData:(NSData *)theData {
Byte *arr = [theData bytes];
NSUInteger begin1 = [self findIndexOf:#"<li>" bArr:arr size:[theData length]]+4;
NSUInteger end1 = [self findIndexOf:#"</li></ol>" bArr:arr size:[theData length]];
Byte *arr1 = arr + begin1;
NSData *temp = [NSData dataWithBytes:arr1 length:end1 - begin1];
return [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
}
As for your particular problem, I would try looking through the data manually using the debugger. Put a breakpoint after you have your array (arr1). When you hit it, open up the GDB console and try this:
print (char *)arr1
With your code, it should print out the string you're trying to get. (With the code I gave above, it won't stop after the . It'll just keep going).
If the result is not what you expect, then there's something wrong with the data, or perhaps with your begin1 and end1 boundaries.