hex a to binary - iphone

i am trying to convert my hex value to binary value , but i am facing little problem .
as i am new trying to learn my faults .
my code :
NSMutableString *str;
NSString *dd = #"192:168:1:2:0B:2:D:00";
NSCharacterSet *donotwant1 = [NSCharacterSet characterSetWithCharactersInString:#":""];
dd =[[dd componentsSeparatedByCharactersInSet:donotwant1] componentsJoinedByString:#" "];
NSMutableArray *array = [[dd componentsSeparatedByString:#" "] mutableCopy];
[array removeObjectAtIndex:0];
//NSLog(#"%#",array);
for (int j=0; j<[array count]; j++) {
NSScanner *scan = [NSScanner scannerWithString:[array objectAtIndex:j]];
unsigned int i=0;
if ([scan scanHexInt:&i]) {
// NSLog(#"numbner is %ustr", i);
}
NSInteger theNumber = i;
str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1) {
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
[array removeObjectAtIndex:j];
[array insertObject:str atIndex:j];
}
}
NSLog(#"Binary version: %#", array);
I'm getting
1,1100,11001111,1111,1111,11101111.....
in my code 0 values are eliminated . i want 8bits like(00000001,00001100.....) can any one tell me the reason

When the most significant bit is reached, your algorithm stops the conversion. Why not force the loop to always execute 8 times?
for (int numberCopy = theNumber, int i = 0; i < 8; numberCopy >>= 1, i++) {
// loop body here
}
By the way, here's a cleaner/shorter/simpler approach that doesn't involve highly superfluous copying and uses characters instead of string objects for hyper efficiency (just kidding, I'm all against micro-optimizations, but I feel like inserting an NSString before another one is unnecessary, especially if the number of bits is known and constant). This also assumes UTF-8 and exploits the fact that hexadecimal and binary representation have a very nice relationship, 16 being the 4th power of 2:
NSString *dd = #"01:0C:CF:0F:EF:AF:BD:00";
NSArray *bytes = [dd componentsSeparatedByString:#":"];
NSMutableArray *binaries = [NSMutableArray array];
NSString *lookup[256];
lookup['0'] = #"0000";
lookup['1'] = #"0001";
lookup['2'] = #"0010";
lookup['3'] = #"0011";
lookup['4'] = #"0100";
lookup['5'] = #"0101";
lookup['6'] = #"0110";
lookup['7'] = #"0111";
lookup['8'] = #"1000";
lookup['9'] = #"1001";
lookup['A'] = #"1010";
lookup['B'] = #"1011";
lookup['C'] = #"1100";
lookup['D'] = #"1101";
lookup['E'] = #"1110";
lookup['F'] = #"1111";
for (NSString *s in bytes) {
unichar n1 = [s characterAtIndex:0];
unichar n0 = [s characterAtIndex:1];
[binaries addObject:[lookup[n1] stringByAppendingString:lookup[n0]]];
}
NSLog(#"%#", binaries);

Related

how to add comma to string after every nth character in xcode

my problem is pretty simple. I assign a value to string variable in xcode which looks like this:
ARAMAUBEBABRBGCNDKDEEEFO
and I need it like this:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO
The length is different in each variable.
thanx in advance
This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps.
//add comas to a a string...
//example1: #"5123" = #"5,123"
//example2: #"123" = #"123"
//example3: #"123123123" = #"123,123,123"
-(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{
NSMutableString *stringFormatted = [NSMutableString stringWithFormat:#"%#",myString];
for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) {
if (i>0) {
[stringFormatted insertString: #"," atIndex: i];
}
}
return stringFormatted;
}
Try this:
int num;
NSMutableString *string1 = [NSMutableString stringWithString: #"1234567890"];
num = [string1 length];
for(int i=3;i<=num+1;i++) {
[string1 insertString: #"," atIndex: i];
i+=3;
}
NSString *yourString; // the string you want to process
int len = 2; // the length
NSMutableString *str = [NSMutableString string];
int i = 0;
for (; i < [yourString length]; i+=len) {
NSRange range = NSMakeRange(i, len);
[str appendString:[yourString substringWithRange:range]];
[str appendString:#","];
}
if (i < [str length]-1) { // add remain part
[str appendString:[yourString substringFromIndex:i]];
}
// str now is what your want
This would work well when your string is not very large:
NSString * StringByInsertingStringEveryNCharacters(NSString * const pString,
NSString * const pStringToInsert,
const size_t n) {
NSMutableString * const s = pString.mutableCopy;
for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) {
[s insertString:pStringToInsert atIndex:pos];
}
return s.copy;
}
If the string is very large, you should favor to compose it without insertion (append-only).
(define your own error detection)

How to sort an array with alphanumeric values?

I have an array which contains strings like frame_10#3x.png , frame_5#3x.png,frame_19#3x.png etc.
So I want to sort this array according to the number after the underscore i.e. the correct sequence will be frame_5#3x.png,frame_10#3x.png,frame_19#3x.png.
I tried to use the following method but no result:
NSInteger firstNumSort(id str1, id str2, void *context) {
int num1 = [str1 integerValue];
int num2 = [str2 integerValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
return NSOrderedSame;
}
Please suggest how to do this sorting for array.
NSArray *sry_img = [[NSArray alloc] initWithObjects:#"frame_18#3x.png",#"frame_17#3x.png",#"frame_1222#3x.png",#"frame_10#3x.png",#"frame_3#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",#"frame_1#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",nil];
NSArray *sortedStrings = [sry_img sortedArrayUsingSelector:#selector(localizedStandardCompare:)];
NSLog(#"%#",sortedStrings);
Enjy .......
But
localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
you want to do something like:
NSArray *components1 = [str1 componentsSeparatedByString:#"_"];
NSArray *components2 = [str2 componentsSeparatedByString:#"_"];
NSString *number1String = [components1 objectAtIndex:([components1 count] - 1])];
NSString *number2String = [components2 objectAtIndex:([components2 count] - 1])];
return [number1String compare:number2String];
I am not sure if my solution is the best possible approach but it can solve your problem for the time being :) .
1) First I have written a function to get the numbers before # character in your string and then I implemented simple SELECTION SORT algo to sort the array using this functions.
- (NSString*)getSubStringForString:(NSString*)value {
// First we will cut the frame_ string
NSMutableString *trimmedString = [NSMutableString stringWithString:[value substringWithRange:NSMakeRange(6, [value length]-6)]];
// New String to contain the numbers
NSMutableString *newString = [[NSMutableString alloc] init];
for (int i = 0; i < [trimmedString length] ; i++) {
NSString *singleChar = [trimmedString substringWithRange:NSMakeRange(i, 1)];
if (![singleChar isEqualToString:#"#"]) {
[newString appendString:singleChar];
} else {
break;
}
}
return newString;
}
This is the selection Implementation of the algo for sorting. The main logic is in the for loop. You can copy the code in viewDidLoad method to test.
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"frame_10#3x.png",#"frame_5#3x.png",
#"frame_3#3x.png", #"frame_19#3x.png",
nil];
NSLog(#"Values before Sort: %#", array);
int iPos;
int iMin;
for (iPos = 0; iPos < [array count]; iPos++)
{
iMin = iPos;
for (int i = iPos+1; i < [array count]; i++)
{
if ([[self getSubStringForString:[array objectAtIndex:i]] intValue] >
[[self getSubStringForString:[array objectAtIndex:iMin]] intValue]) {
iMin = i;
}
}
if ( iMin != iPos )
{
NSString *tempValue = [array objectAtIndex:iPos];
[array replaceObjectAtIndex:iPos withObject:[array objectAtIndex:iMin]];
[array replaceObjectAtIndex:iMin withObject:tempValue];
}
}
NSLog(#"Sorted Values: %#", array);
I hope that it can atleast keep you going. :)
You can try this-
NSString *str1 = [[[[str1 componentsSeparatedByString:#"frame_"] objectAtIndex:1] componentsSeparatedByString:#"#3x.png"] objectAtIndex:0];
int num1 = [str1 integerValue];

How to convert Hex to Binary iphone

I need to convert a hex string to binary form in objective-c, Could someone please guide me?
For example if i have a hex string 7fefff78, i want to convert it to 1111111111011111111111101111000?
BR,
Suppi
Nice recursive solution...
NSString *hex = #"49cf3e";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt]];
-(NSString *)toBinary:(NSUInteger)input
{
if (input == 1 || input == 0)
return [NSString stringWithFormat:#"%u", input];
return [NSString stringWithFormat:#"%#%u", [self toBinary:input / 2], input % 2];
}
Simply convert each digit one by one: 0 -> 0000, 7 -> 0111, F -> 1111, etc. A little lookup table could make this very concise.
The beauty of number bases that are powers of another base :-)
In case you need leading zeros, for example 18 returns 00011000 instead of 11000
-(NSString *)toBinary:(NSUInteger)input strLength:(int)length{
if (input == 1 || input == 0){
NSString *str=[NSString stringWithFormat:#"%u", input];
return str;
}
else {
NSString *str=[NSString stringWithFormat:#"%#%u", [self toBinary:input / 2 strLength:0], input % 2];
if(length>0){
int reqInt = length * 4;
for(int i= [str length];i < reqInt;i++){
str=[NSString stringWithFormat:#"%#%#",#"0",str];
}
}
return str;
}
}
NSString *hex = #"58";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt strLength:[hex length]]];
NSLog(#"binario %#",binary);
I agree with kerrek SB's answer and tried this.
Its work for me.
+(NSString *)convertBinaryToHex:(NSString *) strBinary
{
NSString *strResult = #"";
NSDictionary *dictBinToHax = [[NSDictionary alloc] initWithObjectsAndKeys:
#"0",#"0000",
#"1",#"0001",
#"2",#"0010",
#"3",#"0011",
#"4",#"0100",
#"5",#"0101",
#"6",#"0110",
#"7",#"0111",
#"8",#"1000",
#"9",#"1001",
#"A",#"1010",
#"B",#"1011",
#"C",#"1100",
#"D",#"1101",
#"E",#"1110",
#"F",#"1111", nil];
for (int i = 0;i < [strBinary length]; i+=4)
{
NSString *strBinaryKey = [strBinary substringWithRange: NSMakeRange(i, 4)];
strResult = [NSString stringWithFormat:#"%#%#",strResult,[dictBinToHax valueForKey:strBinaryKey]];
}
return strResult;
}

convert a char to string

my code works great until know and, if I put a double digit number into the text field (like 12) nslog returns 2 single digit numbers (like 1 and 2). Now I need to put these 2 single digit numbers into 2 strings. can somebody help me. thanks in advance.
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
for(int i = 0; i < [firstThird length]; i++)
{
char extractedChar = [firstThird characterAtIndex:i];
NSLog(#"%c", extractedChar);
}
You should be able to use -stringWithFormat:.
NSString *s = [NSString stringWithFormat:#"%c", extractedChar];
EDIT:
You can store them in an array.
NSMutableArray *digits = [NSMutableArray array];
for ( int i = 0; i < [s length]; i++ ) {
char extractedChar = [s characterAtIndex:i];
[digits addObject:[NSString stringWithFormat:#"%c", extractedChar]];
}
Try to print the value of firstThird using NSLog(), see what it exactly hold, you code seem correct,
Use characterAtIndex function for NSString to extract a character at known location
- (unichar)characterAtIndex:(NSUInteger)index
Use as below
NSString *FirstDigit = [NSString stringWithFormat:#"%c", [myString characterAtIndex:0]];
NSString *SecondDigit = [NSString stringWithFormat:#"%c", [myString characterAtIndex:1]];

NSString range of string at occurrence

i'm trying to build a function that will tell me the range of a string at an occurrence.
For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.
I've tried building this simple function, but it doesn't work.
Note - the top functions were constructed at an earlier date and work fine.
Any help appreciated.
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex {
if (toCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = 0; i <= toCharacterIndex; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex {
if (fromCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = (fromCharacterIndex+1); i <= [stringToTrim length]; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence {
NSString *trimmedString = [inString copy]; //We start with the whole string.
NSUInteger len, loc, oldLength;
len = 0;
loc = 0;
NSRange tempRange = [string rangeOfString:substring];
len = tempRange.length;
loc = tempRange.location;
for (int i = 0; i != occurence; i++) {
NSUInteger endOfWord = len+loc;
trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord];
oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length];
NSRange tmp = [trimmedString rangeOfString:substring];
len = tmp.length;
loc = tmp.location + oldLength;
}
NSRange returnRange = NSMakeRange(loc, len);
return returnRange;
}
Instead of trimming the string a bunch of times (slow), just use rangeOfString:options:range:, which searches only within the range passed as its third argument. See Apple's documentation.
So try:
- (NSRange)rangeOfString:(NSString *)substring
inString:(NSString *)string
atOccurence:(int)occurence
{
int currentOccurence = 0;
NSRange rangeToSearchWithin = NSMakeRange(0, string.length);
while (YES)
{
currentOccurence++;
NSRange searchResult = [string rangeOfString: substring
options: NULL
range: rangeToSearchWithin];
if (searchResult.location == NSNotFound)
{
return searchResult;
}
if (currentOccurence == occurence)
{
return searchResult;
}
int newLocationToStartAt = searchResult.location + searchResult.length;
rangeToSearchWithin = NSMakeRange(newLocationToStartAt, string.length - newLocationToStartAt);
}
}
You need to rework the whole code. While it may seem to work, it's poor coding and plain wrong, like permanently reassigning the same variable, initializing but reassigning one line later, releasing after returning (which will never work).
For your question: Just use rangeOfString:options:range:, and do this the appropriate number of times while just incrementing the starting point.