iOS/C: Convert integer into four character string
The type you're talking about is a FourCharCode
, defined in CFBase.h
. It's equivalent to an OSType
. The easiest way to convert between OSType
and NSString
is using NSFileTypeForHFSTypeCode()
and NSHFSTypeCodeFromFileType()
. These functions, unfortunately, aren't available on iOS.
For iOS and Cocoa-portable code, I like Joachim Bengtsson's FourCC2Str()
from his NCCommon.h
(plus a little casting cleanup for easier use):
#include <TargetConditionals.h>
#if TARGET_RT_BIG_ENDIAN
# define FourCC2Str(fourcc) (const char[]){*((char*)&fourcc), *(((char*)&fourcc)+1), *(((char*)&fourcc)+2), *(((char*)&fourcc)+3),0}
#else
# define FourCC2Str(fourcc) (const char[]){*(((char*)&fourcc)+3), *(((char*)&fourcc)+2), *(((char*)&fourcc)+1), *(((char*)&fourcc)+0),0}
#endif
FourCharCode code = 'APPL';
NSLog(@"%s", FourCC2Str(code));
NSLog(@"%@", @(FourCC2Str(code));
You could of course throw the @()
into the macro for even easier use.
How to convert an Int to a Character in Swift
You can't convert an integer directly to a Character
instance, but you can go from integer to UnicodeScalar
to Character
and back again:
let startingValue = Int(("A" as UnicodeScalar).value) // 65
for i in 0 ..< 26 {
print(Character(UnicodeScalar(i + startingValue)))
}
Objective-C int to char
I would recommend use ASCII values and just typecast.
In most cases it is best to just use the ASCII values to encode letters; however if you wanted to use 1 2 3 4 to represent 'a' 'b' 'c' 'd' then you could use the following.
For example, if you wanted to convert the letter 1 to 'a' you could do:
char letter = (char) 1 + 96;
as in ASCII 97 corresponds to the character 'a'. Likewise you can convert the character 'a' to the integer 1 as follows
int num = (int) 'a' - 96;
Of course it is just easier to use ASCII values to start with and avoid adding or subtracting as shown above. :-D
Swift equivalent to Objective-C FourCharCode single quote literals (e.g. 'TEXT')
I'm using this in my Cocoa Scripting apps, it considers characters > 0x80 correctly
func OSTypeFrom(string : String) -> UInt {
var result : UInt = 0
if let data = string.dataUsingEncoding(NSMacOSRomanStringEncoding) {
let bytes = UnsafePointer<UInt8>(data.bytes)
for i in 0..<data.length {
result = result << 8 + UInt(bytes[i])
}
}
return result
}
Edit:
Alternatively
func fourCharCodeFrom(string : String) -> FourCharCode
{
assert(string.count == 4, "String length must be 4")
var result : FourCharCode = 0
for char in string.utf16 {
result = (result << 8) + FourCharCode(char)
}
return result
}
or still swiftier
func fourCharCode(from string : String) -> FourCharCode
{
return string.utf16.reduce(0, {$0 << 8 + FourCharCode($1)})
}
objective c convert int to unsigned char hex
There is no conversion as such; simply cast from int
to unsigned char
:
int x = -4;
unsigned char y = (unsigned char)x;
There is also no hex as such; that's just a formatting option to printf()
or whatever:
printf("y=0x%02x", (unsigned)y);
How do I convert an integer to the corresponding words in objective-c?
Apple has a lot of handy formatting functionality built in for many data types. Called a "formatter," they can convert objects to/from string representations.
For your case, you will be using NSNumberFormatter, but if you have an integer you need to convert it to an NSNumber first. See below example.
NSInteger anInt = 11242043;
NSString *wordNumber;
//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(@"Answer: %@", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three
If you'd like to learn more about formatters:
https://developer.apple.com/library/content/documentation/General/Conceptual/Devpedia-CocoaApp/Formatter.html
Get a char from NSString and convert to int
Many interesting proposals, here.
This is what I believe yields the implementation closest to your original snippet:
NSString *string = @"123123";
NSUInteger i = 3;
NSString *singleCharSubstring = [string substringWithRange:NSMakeRange(i, 1)];
NSInteger result = [singleCharSubstring integerValue];
NSLog(@"Result: %ld", (long)result);
Naturally, there is more than one way to obtain what you are after.
However, As you notice yourself, Objective-C has its shortcomings. One of them is that it does not try to replicate C functionality, for the simple reason that Objective-C already is C. So maybe you'd be better off just doing what you want in plain C:
NSString *string = @"123123";
char *cstring = [string UTF8String];
int i = 3;
int result = cstring[i] - '0';
NSLog(@"Result: %d", result);
Related Topics
How to Get Static Image from Google Maps in iOS
How to Show "Would Like to Send You Push Notifications" Alert View Again
Hit Detection When Drawing Lines in iOS
How to Only Override a Method Depending on the Runtime System iOS Version
Thread 1:Exc_Bad_Access (Code = 1, Address = 0X30000008)
Drawing with Cgpath to Svg Output
Build Video from Uiimage Using Swift
Get Sms Broadcast with Text Body Without Jailbreak But Private Frameworks in iOS
Array of Multiple Url's Nsfilemanager Swift
Itunes Connect: Can't See Build
How to Remove All References for Outlet
Nsinteralinconsistencyexception - Uikeyboardlayoutalignmentview
The 'Pods' Target Has Transitive Dependencies That Include Static Binaries' When Installing Gcm
Usage of String.Range in Swift 3.0
Ms Excel Type Spreadsheet Creation Using Objective-C for iOS App