Conversion from NSString to Hex - objective-c

i am new in this field and i was working on a conversion of NSString to Hex and have been stuck into it. My String lets suppose is 1,FF,F8 now how can i convert that into hex numbers like 0x01,0x0FF and 0x0F8

First step would be to split the string containing "1,FF,F8" into three strings containing the separate hex values, "1", "FF", "F8".
NSString *hexString = #"1,FF,F8";
NSArray *hexValues = [hexString componentsSeparatedByString:#","];
As for the conversion from NSString to hex, I'm not quite sure what exactly you want.
If you just want to add on a "0x0" to the beginning of the hex values, you can just do:
NSMutableArray *formattedHexValues = [NSMutableArray array];
for(NSString *hexValue in hexValues) {
[formattedHexValues addObject:[NSString stringWithFormat:#"0x0%#", hexValue]];
}
If you want to actually get the integer value of the hex string, do this:
for(NSString *hexString in formattedHexValues) {
unsigned int value;
[[NSScanner scannerWithString:hexString] scanHexInt:&value];
NSLog(#"The value is %d", value);
}
Typed this out in the browser so there might be a syntax mistake or two, but it generally should work fine.

Related

Why is this string returning NULL? (Binary conversion)

I am trying to separate the last four digits of an 8bit binary string. In order to do this I have tried to create a new string and appendFormat each of the last four digits of the original string. The only problem is this new string always returns NULL when I know it shouldn't be. Anyone have an idea about what I'm doing wrong?
NSMutableString *str = #"01110001;
unsigned short zero = [str characterAtIndex:0]-48;
unsigned short one = [str characterAtIndex:1]-48;
unsigned short two = [str characterAtIndex:2]-48;
unsigned short three = [str characterAtIndex:3]-48;
unsigned short four = [str characterAtIndex:4]-48;
unsigned short five = [str characterAtIndex:5]-48;
unsigned short six = [str characterAtIndex:6]-48;
unsigned short seven = [str characterAtIndex:7]-48;
NSMutableString *newString;
[newString appendFormat:#"%d%d%d%d",four, five, six, seven];
NSLog(#"NEWSTRING:%#", newString);
Alternatively, is there a better way to get just the last four digits of the original string?
Use the methods of NSString:
NSString *str = #"01110001";
NSString *lastFour = [str substringFromIndex:str.length - 4];
This code assumes that str has at least 4 characters. It will give you the last four no matter how long the string is.
Update to explain the original problem.
You were getting nil because you never initialized newString. It is nil and you call appendFormat: on the nil value which does nothing.
It would have worked if you did:
NSMutableString *newString = [NSMutableString string];
However, neither of your strings need to be mutable.
You should have done:
NSString *newString = [NSString stringWithFormat:#"%d%d%d%d",four, five, six, seven];
Of course, as the beginning of my answer shows, none of that was needed anyway.

Convert a String into an array with Keycodes

today i started with a simple Project that should convert a string into an array with keycodes to simulate keystrokes.
My Problem is that i cant use a char as an id for a dictionary to convert that char into the keycode.
//Declare a Dictionary
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
//Add the Basic data for keycodes (i know that there are some missing)
[dictionary setObject:#"0x00" forKey:#"a"]; //a
[dictionary setObject:#"0x0B" forKey:#"b"]; // b
[dictionary setObject:#"0x08" forKey:#"c"]; //c
[dictionary setObject:#"0x02" forKey:#"d"]; // d
[dictionary setObject:#"0x0E" forKey:#"e"]; //e
[dictionary setObject:#"0x03" forKey:#"f"]; //f
[dictionary setObject:#"0x05" forKey:#"g"]; //g
[dictionary setObject:#"0x04" forKey:#"h"]; //h
[dictionary setObject:#"0x22" forKey:#"i"]; //i
[dictionary setObject:#"0x26" forKey:#"j"]; //j
[dictionary setObject:#"0x28" forKey:#"k"]; //k
[dictionary setObject:#"0x25" forKey:#"l"];//l
[dictionary setObject:#"0x2D" forKey:#"m"];//m
[dictionary setObject:#"0x2E" forKey:#"n"];//n
[dictionary setObject:#"0x1F" forKey:#"o"];//o
[dictionary setObject:#"0x23" forKey:#"p"];//p
[dictionary setObject:#"0x0C" forKey:#"q"];//q
[dictionary setObject:#"0x0F" forKey:#"r"];//r
[dictionary setObject:#"0x01" forKey:#"s"];//s
[dictionary setObject:#"0x11" forKey:#"t"];//t
[dictionary setObject:#"0x20" forKey:#"u"];//u
[dictionary setObject:#"0x09" forKey:#"v"];//v
[dictionary setObject:#"0x0D" forKey:#"w"];//w
[dictionary setObject:#"0x07" forKey:#"x"];//x
[dictionary setObject:#"0x10" forKey:#"y"];//y
[dictionary setObject:#"0x06" forKey:#"z"];//z
NSString *workwith = [_mess stringValue]; //Get String from Interface
long stringl = [workwith length]; //Get lenght of the String
int a = 0;
char text[stringl-1]; //make a array with the lenght of the string
while (a < stringl) { //fill this array with chars from the string
text[a] = [workwith characterAtIndex:a];
NSLog(#"%c",text[a]);
a++;
}
char fmat[stringl-1]; //make a second char to fill it with keycodes
int dnehmen = 0;
while (dnehmen <= stringl-1) {
fmat[dnehmen] = [dictionary objectForKey:#"%c",text[dnehmen]]; //stuck at this point
}
At the last line i try to use a char from the first array as an id for the dictionary to get the keycode for the second array.
I get an error that i cant use a char as an id and so i need a was to get the keycode from a char.
(I read some Posts on this site but i didn`t really understood what they´ve done)
Thanks for your answers
Tim
The error you report is down to the line:
fmat[dnehmen] = [dictionary objectForKey:#"%c",text[dnehmen]];
as #"%c",text[dnehmen] does not return an object but a char value due to the use of the rather obscure C comma operator - a comma is usually a separator but is also an operator (like + etc.) which just returns its second argument. So you get an error referring to characters...
Given that you've used NSString values as keys what you need is a string containing your character and you probably meant to type:
fmat[dnehmen] = [dictionary objectForKey:[NSString stringWithFormat:#"%c",text[dnehmen]]];
While that will fix your first problem you now have another, your dictionary returns an NSString containing four characters and your code suggests you'd like the byte (char) represented by those four characters when interpreted by a compiler as a hexadecimal literal...
At this point you might be tempted to try to convert the string into a byte value by parsing it as a hexadecimal number, but you shouldn't. Instead look at putting the value you need into the NSDictionary in the first place. Both the objects any keys used in an NSDictionary can be any [1] type of object. You might want to consider using NSNumber objects for both.
Hopefully that will set you off on the right track in fixing your design.
[1] Well almost any to be precise, any which have equality and hash methods - which in practice is everything that descends from NSObject so don't worry about this pedantic detail now!

Detect type from string objective-c

Whats the best way of detecting a data type from a string in Objective-c?
I'm importing CSV files but each value is just a string.
E.g. How do I tell that "2.0" is a number, "London" should be treated as a category and that "Monday 2nd June" or "2/6/2012" is a date.
I need to test the datatype some how and be confident about which type I use before passing the data downstream.
Regex is the only thing I can think about, but if you are on mac or iphone, than you might try e.g. RegexKitLite
----------UPDATE----------
Instead of my previous suggestion, try this:
NSString *csvString = #"333";
NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,";
NSScanner *typeScanner = [NSScanner scannerWithString: csvString];
[typeScanner setCharactersToBeSkipped: [NSCharacterSet characterSetWithCharactersInString:charSet]];
NSString *checkString = [[NSString alloc] init];
[typeScanner scanString:csvString intoString:&checkString];
if([csvString length] == [checkString length]){
//the string "csvString" is an integer
}
To check for other types (float, string, etc.), change this line (which checks for int type) NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,"; to NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; (which checks for float type) or NSString *charSet = #"1234567890"; (which checks for a string composed only of letters).
-------Initial Post-------
You could do this:
NSString *stringToTest = #"123";
NSCharacterSet *intValueSet = [NSCharacterSet decimalDigitCharacterSet];
NSArray *test = [stringToTest componentsSeparatedByCharactersInSet:intValueSet];
if ([test count]==[stringToTest length]+1){
NSLog(#"It's an int!");
}
else {
NSLog(#"It's not an int");
}
This works for numbers that don't have a decimal point or commas as thousands separators, like "8493" and "883292837". I've tested it and it works.
Hope this provides a start for you! I'll try to figure out how to test for numbers with decimal points and strings.
Like Andrew said, regular expressions are probably good for this, but they're a bit complicated.

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

iPhone - Splitting an NSString into char NSStrings

I've got a 2d NSArray of {{"foo","food only only"}, {"bar","babies are rad"} ... } and I need to end up with 2 NSArrays: one of characters and one of the corresponding words. So #"f", #"o",#"b",#"a",#"r" and #"food",#"only",#"babies",#"are",#"rad" would be my two NSArray's of NSStrings.
So first, how do I get #"f",#"o",#"o" from #"foo"
And second how can I only keep the uniques? I'm guessing NSDictionary and only add if key is not there giving me #"f":#"food" #"o":#"only" then use getObjects:andKeys: to get two C arrays which I'll convert to NSArrays..
Based on the below answer I went with the following. I didn't actually use the NSMutableDict, I just added my letters to it to get the uniqueness check before creating my 2 output arrays:
unichar ch = [[arr objectAtIndex:0] characterAtIndex:i];
NSString *s = [NSString stringWithCharacters: &ch length: 1];
if (![dict objectForKey:s]) {
}
getCharacters will get you started with an array of characters: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/getCharacters:
You could cycle through and check for uniques after
If you want the individual characters of a string, try -characterAtIndex:. That will get you them as the unichar primitive type, which you can then wrap in NSString like so:
unichar ch = ...;
NSString *chString = [NSString stringWithCharacters: &ch length: 1];
To keep uniques, you can store objects in an NSMutableSet, though it will not preserve the order in which objects are added to it.