Converting long value to unichar* in objective-c - objective-c

I'm storing large unicode characters (0x10000+) as long types which eventually need to be converted to NSStrings. Smaller unicode characters can be created as a unichar, and an NSString can be created using
[NSString stringWithCharacters:(const unichar *)characters length:(NSUInteger)length]
So, I imagine the best way to get an NSString from the unicode long value would be to first get a unichar* from the long value. Any idea on how I might go about doing this?

Is there any reason you are storing the values as longs? For Unicode storage you only need to store the values as UInt32, which would then make it easy to interpret the data as UTF-32 by doing something like this:
int numberOfChars = 3;
UInt32* yourStringBuffer = malloc(sizeof(UInt32) * numberOfChars);
yourStringBuffer[0] = 0x2F8DB; //杞
yourStringBuffer[1] = 0x2318; //⌘
yourStringBuffer[2] = 0x263A; //☺
NSData* stringData = [NSData dataWithBytes:yourStringBuffer length:sizeof(UInt32) * numberOfChars];
//set the encoding according to the current byte order
NSStringEncoding encoding;
if(CFByteOrderGetCurrent() == CFByteOrderBigEndian)
encoding = NSUTF32BigEndianStringEncoding;
else
encoding = NSUTF32LittleEndianStringEncoding;
NSString* string = [[NSString alloc] initWithData:stringData encoding:encoding];
free(yourStringBuffer);
NSLog(#"%#",string);
//output: 杞⌘☺

Related

NSStringEncoding - enum to string to enum

So I'm saving the NSString encoding enum value in a database as a string. This is one of the values:
NSUTF16LittleEndianStringEncoding = 0x94000100,
And I'm saving it as a string with value 0x94000100. My goal is to read this value as an NSString, but then turn it into a value I can use to encode:
NSString* encodingValueAsString = [object objectForKey:kWSWordlistFilesEncodingKey];
// Convert 'encodingValueAsString' to variable 'encoding' that can act as enum
NSString* dataString = [[NSString alloc] initWithData:data
encoding:encoding];
How do I write that missing line?
There's no reason to convert the enum value to/from a string. Just save it and read it back as an int.
But the short answer to your original question is:
NSStringEncoding encoding = [encodingValueAsString intValue];
Wait - that won't work since you are saving the string as the hex value.
You need to use NSScanner:
NSScanner *scanner = [NSScanner scannerWithString:encodingValueAsString];
NSStringEncoding encoding;
[scanner scanHexInt:&encoding];
See why using int instead of a string would be easier?

Get Unicode point of NSString and put that into another NSString

What's the easiest way to get the Unicode value from an NSString? For example,
NSString *str = "A";
NSString *hex;
Now, I want to set the value of hex to the Unicode value of str (i.e. 0041)... How would I go about doing that?
The unichar type is defined to be a 16-bit unicode value (eg, as indirectly documented in the description of the %C specifier), and you can get a unichar from a given position in an NSString using characterAtIndex:, or use getCharacters:range: if you want to fill a C array of unichars from the NSString more quickly than by querying them one by one.
NSUTF32StringEncoding is also a valid string encoding, as are a couple of endian-specific variants, in case you want to be absolutely future proof. You'd get a C array of those using the much more longwinded getBytes:maxLength:usedLength:encoding:options:range:remainingRange:.
EDIT: so, e.g.
NSString *str = #"A";
NSLog(#"16-bit unicode values are:");
for(int index = 0; index < [str length]; index++)
NSLog(#"%04x", [str characterAtIndex:index]);
You can use
NSData * u = [str dataUsingEncoding:NSUnicodeStringEncoding];
NSString *hex = [u description];
You may replace NSUnicodeStringEncoding by NSUTF8StringEncoding, NSUTF16StringEncoding (the same as NSUnicodeStringEncoding) or NSUTF32StringEncoding, or many other values.
See here
for more

Encoding is not giving the right result in objective c

I have a c# code which encodes a string. I am trying to write a corresponding routine in objective c.
The code is as follows:
// c# code
public static string Encode(Guid guid)
{
string encode = convert.ToBase64String(guid.ToByteArray());
encode = encoded.Replace("/","_").Replace("+","-");
return encoded.substring(0,22);
}
I have written this code in objective c.
- (NSString *)encode:(NSString *)inId
{
NSString *uniqueId = inId;
// convert user id in to data
NSData *userIdData = [uniqueId dataUsingEncoding:NSUTF16StringEncoding];
// convert encoded userId's data into base64EncodedString
NSString *base64String = [Base64 encode:userIdData];
//NSString *base64String = [userIdData encodeBase64ForData];
NSString *encodedId = [[NSString alloc] initWithString:base64String];
// replace "/" character in base64String into "_" character
encodedId = [encodedId stringByReplacingOccurrencesOfString:#"/" withString:#"_"];
// replace "+" character in base64String into "-" character
encodedId = [encodedId stringByReplacingOccurrencesOfString:#"+" withString:#"-"];
// get substring of range 22
encodedId = [encodedId substringToIndex:22];
NSLog(#"Base 64 encoded = %#",encodedId);
return encodedId;
}
I am calling this function from viewDidLoad
NSString *encodedStr = [self encode:#"a8f9f344-d14e-4541-a8e7-0f5936e42254"];// string to encode
NSLog(#"Encoded String %#",encodedStr);
this code is not giving me the correct result i want
for eg:for the string a8f9f344-d14e-4541-a8e7-0f5936e42254
it should give result as RPP5qE7RQUWo5w9ZNuQiVA.
Thanks.
Your problem is that guid.ToByteArray() and [uniqueId dataUsingEncoding:NSUTF16StringEncoding]; do not do the same thing. As far as I can tell from the documentation, the former removes the hyphens and treats the rest as the hex ASCII representation of 16 bytes. The latter just turns each character into UTF16 (actually, it is UTF-16 already) and puts it into an NSData.
You need to write some code in Objective-C to take an ASCII Hex string and convert it into bytes.

is it possible to convert NSString into unichar

I have a NSString object and want to change it into unichar.
int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298
NSString *hex = [NSString stringWithFormat:#"0x%x", decimal]; // hex = 0x300a
NSString *chineseChar = [NSString stringWithFormat:#"%C", hex];
// This statement log a different Chinese char every time I run this code
NSLog(#"%#",chineseChar);
When I see the log, It gives different character every time when I run my code.
m I missing something...?
The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.

how to dynamically give buffer value in Objective-C

i ve a string , for example:
NSString *str = #"12,20,40,320,480"
This str has to be given as buffer value,
UInt8 *buffer;
Now how to give the str as buffer value? The value of str string keeps changing , and hence buffer has to dynamically take the value as str everytime.
plz help me how to achieve this.
Thank You.
Your question is pretty unclear but if you want to create an array of UInt8s from a NSString that stores a comma separated list of numbers you have to parse the string to individual numbers and then convert each number's string representation to a UInt8 representation
Something like but with extra code for validating the NSString input:
NSString *str = #"12,20,40,320,480";
NSArray * str_a = [str componentsSeparatedByString:#","];
UInt8 * buf = malloc(sizeof(UInt8) * [str_a count]);
int i;
for(i=0;i<[str_a count];i++)
buf[i] = atoi([[str_a objectAtIndex:i] cStringUsingEncoding:NSASCIIStringEncoding]);
// do something with the buffer
somefunction(buf);
// free the buffer
free(buf);