Trouble converting Dec to Hex (Int to Char) - objective-c

i know this seems to be a stupid question, but i'm really getting trouble here.
I'm working in a project where i have some functions i can´t modify. That is, i got some C functions (not really my speciality) inside my Obj. C code that i can modify.
So here it is... to explain a little what i have.
I'm receiving a NSData like "\xce\x2d\x1e\x08\x08\xff\x7f" . I have to put each \hex code in a char array, like this:
cArray[1]=ce;
cArray[2]=2d;
cArray[3]=1e;
cArray[4]=08;
etc, etc... of course not LIKE THIS, but just so you understand. My initial move was to separe the NSData with subdataWithRange: and fill in an array with all "subdata". So the next move could be passing each position of that array to a char array, and that's where i got stuck.
I'm using something like (dont have my code right now)
for(int i=0 ; i<=64 ; i++) {
[[arrayOfSubData objectAtIndex:i] getBytes:&charArray[i]];
}
To fill the char array with the hex from my array of subData. That works almost perfectly. Almost.
Taking that example of cArray, my NSLog(#"pos%i: %x",i,charArray[i]) would show me:
pos1: ce
pos2: 2d
pos3: 1e
pos4: 8
And all the "left zeros" are supressed in that same way. My workaround for the moment (and i´m not sure if it is the best practice here) is to take my subDataArray and initWithFormat: a string with it. With that i can transform the string to an int with NSScanner scanHexInt:, but then i´m stucked again when converting back my decimal int to a hexadecimal CHAR. What would be the best approach to fill my char array that way?
Any help or some "tough love" will be greatly appreciated. Thanks

According to the normal rules of printf formatting (which NSLog follows also) you want the following:
NSLog(#"pos%i: %02x", i, charArray[i]);
The '0' says to left pad with 0s and is a flag. The '2' says to ensure that output for that field is at least two characters. So that'll ensure that at least two characters are output and pad to the left with '0's in order to fill space.

Related

Format-Specifiers Syntax Error?

i am having a little trouble with printf specifiers...so before asking you guys i read almost everything onC++Reference page, but couldnt fix the problem, and since i am new at c i cant even understand the problem, its most likely a syntax error but i can't find it...
for(i = 1; i <= 10; i++) {
printf("\n%d.%s%n",i,names[i-1],offset);
printf("%*s%.2f TL",10-offset," ",prices[i-1]);
}
so basically i have this code to print a list, and i want the prices to start from the same column.
For e.g:
water 1.00
oj 1.00
and the logic behind my code (incase it's not obvious, i can't tell if it is) is:
print id number and name, count how many chars we've written so far and assign it to offset.
print (starting column of price list)-offset spaces before price
once i couldn't get the result i want, i checked and found out that offset is 3 for all names which is not the case(and no value is assigned to offset before this procedure).
Thanks for any kind of help !
PS: This is a practice code just to get better at using specifiers efficiently.
edit:
so i did this :
for(i=1;i<=10;i++)
{
printf("%d.%s%n",i,names[i-1],&offset);
printf("%*s%.2f TL\n",10-offset," ",prices[i-1]);
}
but what i get as a result is huge empty black command screen.
The %n format specifier requires a pointer. Your code is missing the & operator for offset:
printf("\n%d.%s%n",i,names[i-1],&offset);
The good ol' C interface doesn't know what types you supply to printf so it doesn't complain and happily reads the 4 byte integer value of offset on the stack as a memory location -> core dump.
Actually, g++ with -Wall does warn. So
hd1 has a point here because C++ output is type safe (even though it's a pain);
Heed thy warnings.
When you use %n in a printf format, the corresponding parameter must be a pointer. printf will store the information in the int you point it to.
Assuming you've declared int offset somewhere, you should use &offset as the last argument in your printf call.
While we're here, allow me to comment on this excerpt:
printf("\n
ARGH NO! Newline is a terminator. It goes at the end of a line, not the beginning.
so i did this :
for(i=1;i<=10;i++)
{
printf("%d.%s%n",i,names[i-1],&offset);
printf("%*s%.2f TL\n",10-offset," ",prices[i-1]);
}
but what i get as a result is huge empty black command screen.
edit: Can you guys try this and tell me if you get normal results? I can't understand the mistake occuring, so i can't get past it...Maybe some other examples will lead me to where is the mistake.

How to use hex counting in filenames for programmatic loading?

I have several directories of 12 .caf files and am loading them programmatically:
NSString *soundToPlay = [NSString stringWithFormat:#"sounds/%d/%d_%d.caf", type, note, timbre];
If I want to, say, increment from 9 to 10 in one of those values, suddenly my string is an extra character long, which makes it harder to manipulate later with something like NSMakeRange. I'd like to keep all these %ds to a single character.
What I'd like to do is name my files using the digits 0-9 but then continue with A, B, C instead of 10, 11, 12. This would keep everything single-character. I'm hoping there's an easy way to do this kind of thing, still allowing stuff like increment, +/-, and modulo. If so, what is it?
X is the hexadecimal format specifier:
[NSString stringWithFormat:#"sounds/%X/%X_%X.caf", type, note, timbre]
Alternatively you could always use two digit numbers. That would allow to select from more than 16 cases:
[NSString stringWithFormat:#"sounds/%02d/%02d_%02d.caf", type, note, timbre]

How can I get the actual value of the char instead of the int value

So at first i was trying to use character at index, then convert it to nsnumber, and then get the int value, but for 9 i got a value of 57. So I knew what was going wrong, I'm getting the int of the character itself.
So I read a little, and found atoi, but I get this error, that doesnt crash my app jsut pauses it.
My code is:
int current = atoi([startSquares characterAtIndex: i]);
Now startSquares is a big string full of numbers, and this above line is in a for loop where i goes from 0 to 99.
57 is ASCII for the digit '9'. Assuming that by the "value of the char" you mean "the numeric value of the digit the char represents", you can use the simple trick available in ASCII:
int digit = char - '0';
This trick works, because all digits are encoded in order starting with the digit zero (ASCII code 48). So when you subtract '0' (which is another way to write 48) from 57, you get 9, the value of the digit '9'.
This is a bad design, you should use an int array to hold your squares.
But if you absolutely insist on sticking with your approach, dasblinkenlight's way is the way to go. Just subtract the int value of char '0' from the char that you read.
If you have a character c '9' and you want the numeric value 9, you can use c - '0'. It isn't clear that this is what you want, though.
If you have an array of char that contains a series of numbers (of more than one digit), you need to advance a pointer through that array, and then you could call atoi with that pointer, when it points at a digit (see isdigit), or you could use sscanf, or, you could put it in an NSString and get the next number using intValue. But that would give you an NSInteger, not an NSNumber. I don't think you really want an NSNumber, since you can't directly take the square of one.

How to get a random unicode character in objective C

I was wondering how to get a random Unicode character so that every time this is run it generates a different value. This is what I have so far to get a character:
NSFont *arialUnicode = [[NSFontManager sharedFontManager]
fontWithFamily:#"Arial Unicode MS"
traits:0
weight:5
size:dirtyRect.size.height*0.6];
NSGlyph *glyphs = (NSGlyph *)malloc(sizeof(NSGlyph) * 1);
CTFontGetGlyphsForCharacters((CTFontRef)arialUnicode, (const UniChar *)L"\u2668", (CGGlyph *)glyphs, 1);
It is adapted from a drawing tutorial my friend sent me: http://cocoawithlove.com/2011/01/advanced-drawing-using-appkit.html
Quite a nice tutorial actually :)
But I want to know how to use any character as opposed to just the floral heart. I have found that buy changing the value of 2668 to some other value in the line:
CTFontGetGlyphsForCharacters((CTFontRef)arialUnicode, (const UniChar *)L"\u2668", (CGGlyph *)glyphs, 1);
I can make it change character but i want to automate this so that it automatically chooses different characters.
Thank you
If you truly want a random character, something like
UniChar uc = arc4random() % (0xffffu + 1);
CTFontGetGlyphsForCharacters((CTFontRef)arialUnicode, &uc, (CGGlyph *)glyphs, 1);
But depending on what you are trying to do
There are much easier ways to display text in Cocoa, particularly NSTextField
There are so many characters in Unicode it's highly unlikely a single font will contain all the glyphs.
Do you really want a random unicode code point or do you want to select from a subset of the available characters? See http://www.unicode.org/charts/ to get an idea of just how much Unicode covers.

Store an NSString as a fixed length integer?

having a bit of trouble finding a solution to this.
I want to take a large ordered text file of words and create - in the same order - a text file of fixed length numeric values.
For example:
Input File Output File
AAA -> 00000001
AAH -> 00002718
AAZ -> 71827651
Initially it seemed a hash function would do the trick. However they are one way. Also perhaps they are a bit "heavyweight" for this. After all, I don't need any cryptography. Plus, it's a reference file. It will never change.
Any compression is a bonus not essential. That said, I don't want the file to get any bigger than it already is. Which is why I don't just want to write out the words as text but with fixed lengths.
So, bottom line; input is a NSString of variable length, output is an integer of fixed length. And, I must be able to take the integer and figure out the string.
Any help much appreciated!
Thanks!
xj
Well, this would be a bit of a brute force method, but here's my guess.
Start by making a custom function to convert one letter of text to an integer less than 100. (I'm not sure if such a function already exists, if so then great!) You might need to just go to stuff like "if ([input isEqual: #"a"]){ return 1;}
Then, run that function on each letter of text, and get the final integer by combining the previous results.
For example:
int myVal1 = [intConverter firstLetter];
int myVal2 = [intConverter secondLetter];
int myVal3 = [intConverter thirdLetter];
int finalValue =100^3 + 100^2*myVal1 + 100*myVal2 + myVal3;
Then, finalValue would be of the form 1(myVal1)(myVal2)(myVal3), which is what I think you're looking for.
To get back the original string, simply use the mod (%) and division functions to get the individual values back, then run the intConverter function backwards. (This would probably mean writing a new function that basically runs those if statements in reverse, but oh well.)
I hope this helps.