Converting an NSString to bit value - objective-c

NSString *strVal= #"BAAA";
How do I convert the above string into a bit value? Should I do the byte conversion before this?
Need help on this. I have previously checked this question for integer conversion.

Whether you convert the string to UTF-8 first is up to you; it depends what you want. Internally NSString stores characters as UTF-16 (might be UCS-2 actually) using the unichar type, so you need to decide whether you want the binary of the internal representation or of some other external encoding.
I expect you want the binary of the UTF-8 encoding, so try this (tested):
#import <Foundation/Foundation.h>
#interface BinFuncs : NSObject
+ (NSString *)binaryOfString:(NSString *)str;
#end
#implementation BinFuncs
+ (NSString *)binaryOfString:(NSString *)str {
NSMutableString *binStr = [[NSMutableString alloc] init];
const char *cstr = [str UTF8String];
size_t len = strlen(cstr);
for (size_t i = 0; i < len; i++) {
uint8_t c = cstr[i];
for (int j = 0; j < 8; j++) {
[binStr appendString:((c & 0x80) ? #"1" : #"0")];
c <<= 1;
}
}
return binStr;
}
#end
int main(int argc, const char **argv) {
#autoreleasepool {
for (int i = 1; i < argc; i++) {
NSString *binStr = [BinFuncs binaryOfString:[NSString stringWithUTF8String:argv[i]]];
NSLog(#"%#", binStr);
}
}
return 0;
}
$ clang -o binstr binstr.m -framework Foundation
$ ./binstr 'the quick brown fox jumps over the lazy dog'
2013-09-30 09:19:49.674 binstr[58474:707] 01110100011010000110010100100000011100010111010101101001011000110110101100100000011000100111001001101111011101110110111000100000011001100110111101111000001000000110101001110101011011010111000001110011001000000110111101110110011001010111001000100000011101000110100001100101001000000110110001100001011110100111100100100000011001000110111101100111

Related

Converting NSString to char byte array

In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :
char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};
How to convert my NSString to char byte array like this one?
Thanks!
NSString *strCharData = #"AA010158AA7D385002";
const char *characterRes = [strCharData cStringUsingEncoding:NSUTF8StringEncoding];
or
NSString *strCharData = #"AA010158AA7D385002";
const char *characterRes = [strCharData UTF8String];
Use this answer if i am correct,i did little coding but might be there are possibilities of simpler solutions also like #user3182143
NSString * inputStr = #"AA010158AA7D385002";
NSMutableArray *charByteArray = [[NSMutableArray alloc]initWithCapacity:1];
int i = 0;
for (i = 0; i+2 <= inputStr.length; i+=2) {
NSRange range = NSMakeRange(i, 2);
NSString* charStr = [inputStr substringWithRange:range];
[charByteArray addObject:[NSString stringWithFormat:#"0x%#",charStr]];
}
Output :
char[9] = (
0xAA,
0x01,
0x01,
0x58,
0xAA,
0x7D,
0x38,
0x50,
0x02
)
Since your text is hex and you want actual bytes out (which each correspond to two hex characters), you'll have to manually convert each character into the corresponding number, and then add them together into the correct numerical value.
To do this, I'm taking advantage of the fact that, in ASCII characters, a...z are in a row, as are 0...9. I'm also taking advantage of the fact that hexadecimal is valid ASCII, and that Unicode characters from 0...127 are identical to their corresponding ASCII characters.
Below is a program that does this and prints out the original string's characters as well as the calculated bytes (as hex again):
#import <Foundation/Foundation.h>
int main(int argc, char *argv[])
{
#autoreleasepool
{
NSString *hexStr = #"1234567890abcdef12";
unsigned char theBytes[9] = {};
for( NSUInteger x = 0; x < sizeof(theBytes); x++ )
{
unsigned char digitOne = [hexStr characterAtIndex: x * 2];
if( digitOne >= 'a' )
digitOne -= 'a' -10;
else
digitOne -= '0';
unsigned char digitTwo = [hexStr characterAtIndex: (x * 2) +1];
if( digitTwo >= 'a' )
digitTwo -= 'a' -10;
else
digitTwo -= '0';
printf("%01x%01x",digitOne,digitTwo);
theBytes[x] = (digitOne << 4) | digitTwo;
}
printf("\n");
for( int x = 0; x < sizeof(theBytes); x++ )
printf("%02x",theBytes[x]);
printf("\n");
}
}
Note: This code naïvely assumes that you are providing a correct string. I.e. your input has to consist of lowercase characters and numbers only, and exactly 18 characters. Anything else and you get a wrong result or an exception.
I finally managed to find the answer to my own question. I am posting it here in case it helps someone else.
So I use a method to convert an NSString hex to bytes :
#implementation NSString (HexToBytes)
- (NSData *)hexToBytes
{
NSMutableData *data = [NSMutableData data];
int idx;
for (idx = 0; idx + 2 <= self.length; idx += 2) {
NSRange range = NSMakeRange(idx, 2);
NSString *hexStr = [self substringWithRange:range];
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
#end
And then, I simply use it like that :
NSString *str = #"AA010158AA7D385002";
NSData *databytes = [str hexToBytes];
char *bytePtr = (char *)[databytes bytes];
And I finally get my char array. Hope it helps someone else.

How to solve HackerRank problems in Objective-C

Can anybody explain how to give the hacker rank test in objective-C. Specially the part "Read input from STDIN. Print output to STDOUT"
How to read input and out in objective-c ?
What i have got so far is get input like
NSFileHandle *fileHandler = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [fileHandler availableData];
NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
But to print output, following does not print anything on HackerRank console (but works flawlessly on Xcode console)
NSFileHandle* fileHandler=[NSFileHandle fileHandleWithStandardOutput];
[fileHandler writeData: [formattedString dataUsingEncoding: NSNEXTSTEPStringEncoding]];
The simplest possible way to "Read input from STDIN. Print output to STDOUT" would be to use scanf and printf.
Here's a sample template to get you started:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int count;
scanf("%d", &count);
NSMutableArray *inputIntegers = [NSMutableArray new];
for (int i=0; i<count; i++) {
int inputElement;
scanf("%d", &inputElement);
[inputIntegers addObject:[NSNumber numberWithInt:inputElement]];
}
//to print a specific element:
printf("printing element 0: %d", (int)[inputIntegers[0] integerValue]);
[pool drain];
return 0;
}
Before you take a shot at this journey, a few things:
Make sure ARC is disabled (search for CLANG_ENABLE_OBJC_ARC in build settings, and set it to NO)
Avoid using self. This is functional programming.
Use C functions, not Objective-C methods, meaning, use
instead of
- (NSInteger)sumOfNumbers : (NSInteger)a and:(NSInteger)b {
return a + b;
}
use
int sumOfNumbers(int a, int b){
return a + b;
}
Happy Programming.
Having just been handed one of these tests, I opted to get out of main.m immediately and into Objective-C like so:
#import <Foundation/Foundation.h>
//Objective-C helper class to take over from main.m
//.h
#interface MainClass : NSObject
+ (BOOL)startMain;
#end
//.m
#implementation MainClass
+ (BOOL)startMain {
//Read the STDIN here using the Objective-C wrapper methods
NSInteger n = [self readInt];
[self printInt:n];
NSArray *numbers = [self readIntArrayOfLength:n];
[self printIntNumberArray:numbers];
return YES;
}
+ (NSInteger)readInt {
int n;
scanf("%i",&n);
return n;
}
+ (NSArray *)readIntArrayOfLength:(NSInteger)len {
NSMutableArray *result = [NSMutableArray array];
for (int i =0; i < len; i++) {
[result addObject:[NSNumber numberWithInt:[self readInt]]];
}
return [result copy];
}
//Helpers to print an int and array of ints to STDOUT
+ (void)printInt:(NSInteger)i {
printf("%li\n",(long)i);
}
+ (void)printIntNumberArray:(NSArray *)array {
printf("[");
[array enumerateObjectsUsingBlock:^(NSNumber *n, NSUInteger idx, BOOL * _Nonnull stop) {
printf("%li",(long)[n integerValue]);
if (idx < array.count-1) {
printf(",");
}
}];
printf("]\n");
}
#end
//This is what will actually run when you hit "Run Code"
int main(int argc, char * argv[]) {
#autoreleasepool {
return [MainClass startMain];
}
}
Now you can do whatever you like from here using Objective-C.
So in this example a sample input of:
3
11 2 4
Would produce this output:
3
[11,2,4]
Not useful in of itself but illustrates the successful read.
It's a lot simpler in Swift, but here's code to accomplish the same thing anyway:
func readInt() -> Int? {
if let ln = readLine() {
return Int(ln)
}
return nil
}
func readIntArray() -> [Int]? {
if let ln = readLine() {
return ln.characters.split(" ").filter({ Int(String($0)) != nil }).map({ Int(String($0))! })
}
return nil
}
let n = readInt()!
let array = readIntArray()!
print(n)
print(array)
The functions return optionals because even though you are going to force-unwrap the input, better the crash for a nil optional happens in your code than the boilerplate.
#import <Foundation/Foundation.h>
int sum(int a, int b) {
return a + b;
}
int main() {
#autoreleasepool {
int T;
int A;
int B;
printf("Enter number of test cases: ");
scanf("%d", &T);
for (int i=0; i < T; i++) {
scanf("%d", &A);
scanf("%d", &B);
printf("%d\n", sum(A,B));
}
}
return 0;
}
That ought to do it.
Your question is really too general for SO, do not be surprised if it gets closed soon. You need in general to ask specific questions, show what you've tried, etc. But if you're just after a few hints to get you going...
You don't say whether you are a programmer already or know Objective-C in particular, assuming both:
In Xcode look at the Command Line Tool project type
Look into NSFileHandle and its methods, e.g. fileHandleWithStandardInput
Note you can also use the C stdio functions, converting C-style to Objective-C styles strings etc. as needed.
I created github repo with some hackerrank problem solutions written in objective-c. It is on the beginning stage, feel free to contribute by adding your solutions as well.
HackerRank for Objective-C
Since Objective-C is a superset of C, you can use C methods for reading and printing out:
NSInteger n;
char *input[25];
NSMutableArray *strings = [NSMutableArray array];
NSString *s;
NSString *temp;
scanf("%lu", &n);
for (NSInteger i = 0; i < n; ++i) {
scanf("%s", input);
s = [NSString stringWithUTF8String:input];
[inputs addObject:s];
}
If n is of type int, you can read it as:
scanf("%d", &n);

Objective C Pointers

I am experiencing a very odd problem with pointers. As you could see from the below code, I am using a method that generates a random 4 by 4 character grid. It return a pointer to a two dimensional character array. The problem is that when i try to assign the returned pointer to another pointer and try to print the generated grid, I get just one strange symbol.
Header File
#import <Foundation/Foundation.h>
#interface GridGenerator : NSObject
{
}
-(char (*)[4]) generateGrid;
-(int (*)[2]) bbb;
-(void) print;
#end
Implementation File
#import "GridGenerator.h"
#implementation GridGenerator
-(char (*)[4])generateGrid{
char vowels[6] = {'A','E','I','O','U','Y'};
char consonants[20] = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Z'};
char grid[4][4];
int vowelsLength = (sizeof vowels / sizeof vowels[0]);
int consLength = (sizeof consonants / sizeof consonants[0]);
int gridSize = (sizeof grid / sizeof grid[0]);
for(int i=0;i<gridSize;i++){
int vowelsInGridRow = 0;
int noOfVowels = (arc4random() % 2) + 1;
for(int j=0;j<gridSize;j++){
if(noOfVowels != vowelsInGridRow){
int vowIndex = arc4random() % vowelsLength;
char s = vowels[vowIndex];
grid[i][j] = s;
vowelsInGridRow++;
}
else{
int consIndex = arc4random() % consLength;
char s = consonants[consIndex];
grid[i][j] = s;
}
}
}
char (*sd)[4]= grid;
return sd;
}
-(void)print{
char (*grid)[4] = [self generateGrid];
NSString *s = #"\n";
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
s = [s stringByAppendingString:[NSString stringWithFormat:#"%c",grid[i][j]]];
}
s = [s stringByAppendingString:#"\n"];
}
NSLog(#"%#",s);
}
Main File(Test)
#import <Foundation/Foundation.h>
#import "Crossword.h"
#import "GridGenerator.h"
int main(int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GridGenerator *gen = [[GridGenerator alloc] init];
[gen print];
[pool release];
return 0;
}
When I run the code, you can see the result below. After the 'U' there is an inverted question mark(could not be pasted here).
2013-06-02 11:24:29.923 CrosswordTest[646:303]
U
Do you have an idea, what could causes this to happen? I am struggling already for several hours and I cannot find any explanation.
You are returning a reference to a temporary. Explosion (undefined behavior) should be expected.
Workaround. Create a structure:
typedef struct {char at[4][4];} t_grid;
Then populate and return the t_grid by value:
- (t_grid)generateGrid
{
char vowels[6] = {'A','E','I','O','U','Y'};
char consonants[20] = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Z'};
t_grid grid;
...
int gridSize = (sizeof grid.at / sizeof grid.at[0]);
...
grid.at[i][j] = s;
...
return grid;
}
- (void)print
{
t_grid grid = [self generateGrid];
...
Note that you should not use this approach for large arrays or variable length arrays. 4*4 octets is small.

Generate a random alphanumeric string in Cocoa

I want to call a method, pass it the length and have it generate a random alphanumeric string.
Are there any utility libraries out there that may have a bunch of these types of functions?
Here's a quick and dirty implementation. Hasn't been tested.
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-(NSString *) randomStringWithLength: (int) len {
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++) {
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
}
return randomString;
}
Not exactly what you ask, but still useful:
[[NSProcessInfo processInfo] globallyUniqueString]
Sample output:
450FEA63-2286-4B49-8ACC-9822C7D4356B-1376-00000239A4AC4FD5
NSString *alphabet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
NSMutableString *s = [NSMutableString stringWithCapacity:20];
for (NSUInteger i = 0U; i < 20; i++) {
u_int32_t r = arc4random() % [alphabet length];
unichar c = [alphabet characterAtIndex:r];
[s appendFormat:#"%C", c];
}
Surely you can make this shorter:
+(NSString*)generateRandomString:(int)num {
NSMutableString* string = [NSMutableString stringWithCapacity:num];
for (int i = 0; i < num; i++) {
[string appendFormat:#"%C", (unichar)('a' + arc4random_uniform(26))];
}
return string;
}
If you're willing to limit yourself to hex characters only, then the simplest option is to generate a UUID:
NSString *uuid = [NSUUID UUID].UUIDString;
Example output: 16E3DF0B-87B3-4162-A1A1-E03DB2F59654.
If you want a smaller random string then you can grab just the first 8 characters.
It's a version 4 UUID which means the first character in the 3rd and 4th group is not random (they will always be 4 and one of 8, 9, A or B).
Every other character in the string is fully random and you can generate millions of UUIDs every second for hundreds of years without much risk of the same UUID being generated twice.
A category version of Jeff B's answer.
NSString+Random.h
#import <Foundation/Foundation.h>
#interface NSString (Random)
+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length;
#end
NSString+Random.m
#import "NSString+Random.h"
#implementation NSString (Random)
+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length
{
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
for (int i = 0; i < length; i++) {
[randomString appendFormat:#"%C", [letters characterAtIndex:arc4random() % [letters length]]];
}
return randomString;
}
#end
You could also just generate a UUID. While not truly random, they are complex and unique which makes them appear random for most uses. Generate one as a string and then take a range of characters equal to the passed length.
Swift
func randomStringWithLength(length: Int) -> String {
let alphabet = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let upperBound = UInt32(count(alphabet))
return String((0..<length).map { _ -> Character in
return alphabet[advance(alphabet.startIndex, Int(arc4random_uniform(upperBound)))]
})
}
Here's a different way to tackle it. Instead of using a prepared string of characters, you can cast between integers and characters, and generate a dynamic list of characters to select. It's pretty lean and fast, but has a bit more code.
int charNumStart = (int) '0';
int charNumEnd = (int) '9';
int charCapitalStart = (int) 'A';
int charCapitalEnd = (int) 'Z';
int charLowerStart = (int) 'a';
int charLowerEnd = (int) 'z';
int amountOfChars = (charNumEnd - charNumStart) + (charCapitalEnd - charCapitalStart) + (charLowerEnd - charLowerStart); // amount of the characters we want.
int firstGap = charCapitalStart - charNumEnd; // there are gaps of random characters between numbers and uppercase letters, so this allows us to skip those.
int secondGap = charLowerStart - charCapitalEnd; // similar to above, but between uppercase and lowercase letters.
// START generates a log to show us which characters we are considering for our UID.
NSMutableString *chars = [NSMutableString stringWithCapacity:amountOfChars];
for (int i = charNumStart; i <= charLowerEnd; i++) {
if ((i >= charNumStart && i <= charNumEnd) || (i >= charCapitalStart && i <= charCapitalEnd) || (i >= charLowerStart && i <= charLowerEnd)) {
[chars appendFormat:#"\n%c", (char) i];
}
}
NSLog(#"chars: %#", chars);
// END log
// Generate a uid of 20 characters that chooses from our desired range.
int uidLength = 20;
NSMutableString *uid = [NSMutableString stringWithCapacity:uidLength];
for (int i = 0; i < uidLength; i++) {
// Generate a random number within our character range.
int randomNum = arc4random() % amountOfChars;
// Add the lowest value number to line this up with a desirable character.
randomNum += charNumStart;
// if the number is in the letter range, skip over the characters between the numbers and letters.
if (randomNum > charNumEnd) {
randomNum += firstGap;
}
// if the number is in the lowercase letter range, skip over the characters between the uppercase and lowercase letters.
if (randomNum > charCapitalEnd) {
randomNum += secondGap;
}
// append the chosen character.
[uid appendFormat:#"%c", (char) randomNum];
}
NSLog(#"uid: %#", uid);
// Generate a UID that selects any kind of character, including a lot of punctuation. It's a bit easier to do it this way.
int amountOfAnyCharacters = charLowerEnd - charNumStart; // A new range of characters.
NSMutableString *multiCharUid = [NSMutableString stringWithCapacity:uidLength];
for (int i = 0; i < uidLength; i++) {
// Generate a random number within our new character range.
int randomNum = arc4random() % amountOfAnyCharacters;
// Add the lowest value number to line this up with our range of characters.
randomNum += charNumStart;
// append the chosen character.
[multiCharUid appendFormat:#"%c", (char) randomNum];
}
NSLog(#"multiCharUid: %#", multiCharUid);
When I'm doing random character generation, I prefer to work directly with integers and cast them over, instead of writing out the list of chars that I want to draw from. Declaring the variables at the top makes it more system independent, but this code assumes that numbers will have a lower value than letters, and that uppercase letters will have a lower value than lowercase letters.
Alternative solution in Swift
func generateString(len: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let lettersLength = UInt32(countElements(letters))
let result = (0..<len).map { _ -> String in
let idx = Int(arc4random_uniform(lettersLength))
return String(letters[advance(letters.startIndex, idx)])
}
return "".join(result)
}
Modification of a few ideas here, and in done Swift 4.0
extension String
{
subscript (i: Int) -> Character
{
return self[index(startIndex, offsetBy:i)]
}
static func Random(length:Int=32, alphabet:String="ABCDEF0123456789") -> String
{
let upperBound = UInt32(alphabet.count)
return String((0..<length).map { _ -> Character in
return alphabet[Int(arc4random_uniform(upperBound))]
})
}
}
Usage:
let myHexString = String.Random()
let myLongHexString = String.Random(length:64)
let myLettersString = String.Random(length:32, alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ")
If you want a random unicode string, you can create random bytes and then use the valid ones.
OSStatus sanityCheck = noErr;
uint8_t * randomBytes = NULL;
size_t length = 200; // can of course be variable
randomBytes = malloc( length * sizeof(uint8_t) );
memset((void *)randomBytes, 0x0, length);
sanityCheck = SecRandomCopyBytes(kSecRandomDefault, length, randomBytes);
if (sanityCheck != noErr) NSLog(#"Error generating random bytes, OSStatus == %ld.", sanityCheck);
NSData* randomData = [[NSData alloc] initWithBytes:(const void *)randomBytes length: length];
if (randomBytes) free(randomBytes);
NSString* dataString = [[NSString alloc] initWithCharacters:[randomData bytes] length:[randomData length]]; // create an NSString from the random bytes
NSData* tempData = [dataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; // remove illegal characters from string
NSString* randomString = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
The conversion from NSString to NSData and back is necessary to get a valid UTF-8 string.
Be aware that length will not necessarily be the length of the the NSString created in the end.
I did this using a simple char[] instead of an NSString * for the alphabet. I added this to a NSString category.
static const char __alphabet[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
+ (NSString *)randomString:(int)length
{
NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
u_int32_t alphabetLength = (u_int32_t)strlen(__alphabet);
for (int i = 0; i < length; i++) {
[randomString appendFormat:#"%c", __alphabet[arc4random_uniform(alphabetLength)]];
}
return randomString;
}
Adding to good answer given by Melvin, here is a function I made (in SWIFT!) to get a random string:
func randomStringOfLength(length:Int)->String{
var wantedCharacters:NSString="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789"
var s=NSMutableString(capacity: length)
for (var i:Int = 0; i < length; i++) {
let r:UInt32 = arc4random() % UInt32( wantedCharacters.length)
let c:UniChar = wantedCharacters.characterAtIndex( Int(r) )
s.appendFormat("%C", c)
}
return s
}
Here is a test result from calling randomStringOfLength(10): uXa0igA8wm
static NSUInteger length = 32;
static NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString * randomString = [NSMutableString stringWithCapacity:length];
for (NSInteger i = 0; i < length; ++i) {
[randomString appendFormat: #"%C", [letters characterAtIndex:(NSUInteger)arc4random_uniform((u_int32_t)[letters length])]];
}
Generates lowercase alphanumeric random string with given length:
-(NSString*)randomStringWithLength:(NSUInteger)length
{
NSMutableString* random = [NSMutableString stringWithCapacity:length];
for (NSUInteger i=0; i<length; i++)
{
char c = '0' + (unichar)arc4random()%36;
if(c > '9') c += ('a'-'9'-1);
[random appendFormat:#"%c", c];
}
return random;
}
Method to call:
NSString *string = [self stringWithRandomSuffixForFile:#"file.pdf" withLength:4]
Method:
- (NSString *)stringWithRandomSuffixForFile:(NSString *)file withLength:(int)length
{
NSString *alphabet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSString *fileExtension = [file pathExtension];
NSString *fileName = [file stringByDeletingPathExtension];
NSMutableString *randomString = [NSMutableString stringWithFormat:#"%#_", fileName];
for (int x = 0; x < length; x++) {
[randomString appendFormat:#"%C", [alphabet characterAtIndex: arc4random_uniform((int)[alphabet length]) % [alphabet length]]];
}
[randomString appendFormat:#".%#", fileExtension];
NSLog(#"## randomString: %# ##", randomString);
return randomString;
}
Results:
## randomString: file_Msci.pdf ##
## randomString: file_xshG.pdf ##
## randomString: file_abAD.pdf ##
## randomString: file_HVwV.pdf ##
for Swift 3.0
func randomString(_ length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
#define ASCII_START_NUMERS 0x30
#define ASCII_END_NUMERS 0x39
#define ASCII_START_LETTERS_A 0x41
#define ASCII_END_LETTERS_Z 0x5A
#define ASCII_START_LETTERS_a 0x61
#define ASCII_END_LETTERS_z 0x5A
-(NSString *)getRandomString:(int)length {
NSMutableString *result = [[NSMutableString alloc]init];
while (result.length != length) {
NSMutableData* data = [NSMutableData dataWithLength:1];
SecRandomCopyBytes(kSecRandomDefault, 1, [data mutableBytes]);
Byte currentChar = 0;
[data getBytes:&currentChar length:1];
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (currentChar > ASCII_START_NUMERS && currentChar < ASCII_END_NUMERS) { // 0 to 0
[result appendString:s];
continue;
}
if (currentChar > ASCII_START_LETTERS_A && currentChar < ASCII_END_LETTERS_Z) { // 0 to 0
[result appendString:s];
continue;
}
if (currentChar > ASCII_START_LETTERS_a && currentChar < ASCII_END_LETTERS_z) { // 0 to 0
[result appendString:s];
continue;
}
}
return result;
}
Modification for keithyip's answer:
+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length
{
static NSString * const letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
srand(time(NULL));
});
NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
for (int i = 0; i < length; i++) {
[randomString appendFormat:#"%C", [letters characterAtIndex:arc4random() % [letters length]]];
}
return randomString;
}

How do I convert NSString with Hexvalue to binary char*?

I have a long hex value stored as a NSString, something like:
c12761787e93534f6c443be73be31312cbe343816c062a278f3818cb8363c701
How do I convert it back into a binary value stored as a char*
This is a little sloppy, but should get you on the right track:
NSString *hexString = #"c12761787e93534f6c443be73be31312cbe343816c062a278f3818cb8363c701";
char binChars[128]; // I'm being sloppy and just making some room
const char *hexChars = [hexString UTF8String];
NSUInteger hexLen = strlen(hexChars);
const char *nextHex = hexChars;
char *nextChar = binChars;
for (NSUInteger i = 0; i < hexLen - 1; i++)
{
sscanf(nextHex, "%2x", nextChar);
nextHex += 2;
nextChar++;
}
There was a thread on this (or on a very similar) hexadecimal conversion topic a couple of weeks back over on one of the Cocoa mailing lists.
I can't reasonably reproduce the full discussion here (long thread), but the message that starts off the thread is here:
http://www.cocoabuilder.com/archive/message/cocoa/2009/5/9/236391
I do wish there were a Cocoa method for this task, but (pending finding that or pending its implementation) the code (by Mr Gecko, posted at http://www.cocoabuilder.com/archive/message/cocoa/2009/5/10/236424) looks like it would work here.
static NSString* hexval(NSData *data) {
NSMutableString *hex = [NSMutableString string];
unsigned char *bytes = (unsigned char *)[data bytes];
char temp[3];
int i = 0;
for (i = 0; i < [data length]; i++) {
temp[0] = temp[1] = temp[2] = 0;
(void)sprintf(temp, "%02x", bytes[i]);
[hex appendString:[NSString stringWithUTF8String: temp]];
}
return hex;
}