How to convert decimal into octal in objective c - objective-c

just like my question, How can i convert decimal into octal in objective c?
can somebody help me? it's make me dizy

You have to initialize a new NSString object using the right format specifier.
Like :
int i = 9;
NSString *octalString = [NSString stringWithFormat:#"%o", i]; // %O works too.
This will create an autoreleased NSString object containing octal string representation of i. In case you start from a NSString
containing a decimal number representation, you should first retrieve the number using :
int i = [myDecimalNumberAsAString intValue];
Here is a link to the format specifiers reference.
Hope this helps.

Since Objective C is a superset of C you can just use C functions such as sprintf, e.g.
char s[32];
int n = 42;
sprintf(s, "%o", n);

Related

How to define a variable string format specifier

I have this line of code
// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: #"%.10Lg", valueX];
This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.
I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %# because %.10Lg is a format specifier by itself.
OK, I can create a bunch of strings like #"%.5Lg", #"%.8Lg", #"%.9Lg"... and switch that, but I wonder if there is another way...
There is, if you read the manual pages for format specifiers. You can replace the precision with *, which means it will get taken from a parameter instead.
int numDigits = 10;
NSString *value = [NSString stringWithFormat:#"%.*Lg", numDigits, valueX];
I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:
- (NSString *) stringFromValue: (long double) value digits: (int) digits; {
//First create a format string. Use "%%" to escape the % escape char.
NSString *formatString =[NSString stringWithFormat: #"%%.%dLg", digits];
return [NSString stringWithFormat: formatString, value];
}

objective-c - Why can I assign values to pointers?

I understand pointers work with addresses and not the data itself. This is why I need to use the address-of (&) operator below as I need to assign the address of num to the pointer and not the actual value of num (40).
int num = 40;
int *numPtr = #
Therefore i'm confused as to why I can do this.
NSString *str = #"hello";
I've created a pointer str but instead of giving it an address i'm able to assign it some data, a literal string.
I thought pointers could only hold memory addresses so why am I able to directly assign it some data?
For someone trying to get their head around pointers and objects this is very confusing.
No you are not assigning a literal string to it, # makes a NSString object with the string value hello.
In most C languages strings are just an array of char, where char is a primitive type like int like in your example.
There is a reason you put an # before string literals (when you want an NSString and not a C string) in objective-c
#"String" is basically equivalent to [NSString stringWithCString:"string"] which returns a pointer to an NSString object containing the value "string"
It is the same way 1 is a c type integer, but #1 is a NSNumber representing the value of 1. If you see an # it means "this is shorthand for creating an object". (#[] for NSArrays, #{} for NSDictionarys, #(), #123, #YES, #NO for NSNumbers, and #"" for NSString)
C does not have strings. Usually char arrays are used to represent them.
NSString *str = #"hello";
can be thought of as short hand (literal) for:
char charArray[] = "hello";
NSString *str = [[NSString alloc] initWithBytes:charArray length:sizeof(charArray) encoding:NSUTF8StringEncoding]; // disregard character encoding for this example
or
unichar bla[] = {'h', 'e', 'l', 'l', 'o'};
str = [[NSString alloc] initWithCharacters:bla length:sizeof(bla)];
So an object is created and thus you need a pointer.

Concatenate integers and strings in Objective C

Please forgive the simplicity of the question. I'm completely new to Objective C.
I'd like to know how to concatenate integer and string values and print them to the console.
This is what I'd like for my output:
10 + 20 = 30
In Java I'd write this code to produce the needed results:
System.Out.Println(intVarWith10 + " + " + intVarWith20 + " = " + result);
Objective-C is quite different. How can we concatenate the 3 integers along with the strings in between?
You can use following code
int iFirst,iSecond;
iFirst=10;
iSecond=20;
NSLog(#"%#",[NSString stringWithFormat:#"%d + %d =%d",iFirst,iSecond,(iFirst+iSecond)]);
Take a look at NSString - it has a method stringWithFormat that does what you require. For example:
NSString* yString = [NSString stringWithFormat:#"%d + %d = %d",
intVarWith10, intVarWith20 , result];
You can use C style syntax, with NSLog (If you just need to print)
NSLog(#"%d+%d=%d",intvarWith10,intvarWith20,result);
If you want a string variable holding the value
NSString *str = [NSString stringWithFormat:#"%d+%d=%d",intvarWith10,intvarWith20,result];
You have to create an NSString with format and specify the data type.
Something like this :
NSInteger firstOperand=10;
NSInteger secondOperand=20;
NSInteger result=firstOperand+secondOperand;
NSString *operationString=[NSString stringWithFormat:#"%d + %d = %d",firstOperand,secondOperand,result];
NSLog(#"%#",operationString);
NSString with format follows the C printf syntax
Check below code :
int i = 8;
NSString * tempStr = [NSString stringWithFormat#"Hello %d",i];
NSLog(#"%#",tempStr);
I strongly recommend you this link Objective-C Reference.
The Objective-C int data type can store a positive or negative whole number. The actual size or range of integer that can be handled by the int data type is machine and compiler implementation dependent.
So you can store like this.
int a,b;
a= 10;
b= 10;
then performing operation you need to first understand NSString.
C style character strings are composed of single byte characters and therefore limited in the range of characters that can be stored.
int C = a + b;
NSString *strAnswer = [NSString stringWithFormat:#"Answer %d + %d = %d", a , b, c];
NSLog(#"%#",strAnswer)
Hope this will help you.

NSString (or NSArray or something) to variable parameter list of C (char *) strings

Is there any easy way to convert an Objective-C holding class of NSStrings into parameters for a function accepting a variable list of char *? Specifically I have a function like:
-(void)someFunction:(NSSomething *) var
that I want to forward to a C function like
void someCFunction(char * var, ...)
Is there an easy way to go about this?
No, you can only do what you want if the number of arguments you're passing is known at compile time. If you just want to convert a single string, use the -UTF8String message:
// Example with two strings
NSString *str1 = ...;
NSString *str2 = ...;
someCFunction([str1 UTF8String], [str2 UTF8String]); // etc.
But if the number of strings will vary at runtime, you'll need to use a different API, if one is available. For example, if there's an API that took an array of strings, you could convert the Objective-C array into a C array:
// This function takes a variable number of strings. Note: in C/Objective-C
// (but not in C++/Objective-C++), it's not legal to convert 'char **' to
// 'char *const *', so you may sometimes need a cast to call this function
void someCFunction(const char *const *stringArray, int numStrings)
{
...
}
...
// Convert Objective-C array to C array
NSArray *objCArray = ...;
int numStrings = [objCArray count];
char **cStrArray = malloc(numStrings * sizeof(char*));
for (int i = 0; i < count; i++)
cStrArray[i] = [[objCArray objectAtIndex:i] UTF8String];
// Call the function; see comment above for note on cast
someCFunction((const char *const *)cStrArray, numStrings);
// Don't leak memory
free(cStrArray);
This would do the trick:
NSString *string = #"testing string"
const char * p1=[string UTF8String];
char * p2;
p2 = const_cast<char *>(p1);
Yes, this can be done, and is explained here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
And here:
http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
With modifications for ARC here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
Also, variable arguments are not statically or strongly typed, as the other poster seems to be suggesting. In fact, there is no clear indication in the callee of how many arguments you really have. Determining the number of arguments generally breaks down into having to either specify the number by an count parameter, using a null terminator, or inferring it from a format string a la (s)print* . This is frankly why the C (s)print* family of functions has been the source of many errors, now made much much safer by the XCode / Clang / GCC compiler that now warns.
As an aside, you can approach statically typed variable arguments in C++ by creating a template method that accepts an array of an unspecified size. This is generally considered bad form though as the compiler generates separate instances for each size of array seen by by the compiler (template bloat).

Map char to int in Objective-C

I have a need to map char values to int values in Objective-C. I know NSDictionary is out because it deals with reference types, and these are values. The map will be used while iterating through an NSString. Each character in the string will be converted to an integer value. All the integers will be summed together.
Using NSDictionary seems like a bad fit because of all the type coercion I'd have to do. (Converting values types, char and int, to reference types.)
I figure I'll have to drop down to C to do this, but my experience with C libraries is very limited.
Is there something most C developers use that will map char values to int values?
Edit for clarification
The C# equivalent would be a Dictionary<char,int>.
In pseudocode, I'd like to the following:
for (int i = 0; i < [string length]; i++) {
char current = [string characterAtIndex:i];
int score = map[current]; // <- I want map without boxing
// do something with score
}
Char to int?
char aChar = 'a';
int foo = (int) aChar;
Done. No need for a hash or anything else. Even if you wanted to map char -> NSNumber, an array of 256 char's (char being a signed 8 bit type) is very little overhead.
(Unless I entirely misparsed your question -- are you asking for (char*)? ... i.e. C strings? Show some code.).
If I understand correctly, you want to store chars and ints in a dictionary, as keys and values. However, NSDictionary only accepts objects. The solution? Wrap the chars and ints in the NSNumber object:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1],
[NSNumber numberWithChar:'a'],
[NSNumber numberWithInt:2],
[NSNumber numberWithChar:'b'],
nil];
Or if you don't want boxing, why not just make a function that takes chars and returns ints?
int charToScore(char character)
{
switch (character) {
case 'a':
return 1;
case 'b':
return 2;
default:
return 0;
}
}
#Pontus has the correct answer in Objective-C, but if you're willing to use C++, you can use std::map<char, int> (or the still-slightly-nonstandard unordered_map<char, int>.)
To use C++ from within Objective-C, you must rename the file from Whatever.m to Whatever.mm--this tells GCC that the file contains Objective-C++, which allows you to use the Objective-C syntax with C++ underpinnings.