NSData in base 10 [duplicate] - ios

This question already has answers here:
Printing NSData using NSLog
(5 answers)
Closed 9 years ago.
Is it possible to NSLog NSData in base 10. Basically to see byte array of NSData.
I would like to see output something like this: [51, -55, 55, -54, -110]

You can define a category on NSData to produce a string with decimal data representation, like this:
#interface NSData (DecimalOutput)
-(NSString*)asDecimalString;
#end
#implementation NSData (DecimalOutput)
-(NSString*)asDecimalString {
NSMutableString *res = [NSMutableString string];
[res appendString:#"["];
// Construct an `NSString`, for example by appending decimal representations
// of individual bytes to the output string
const char *p = [self bytes];
NSUInteger len = [self length];
for (NSUInteger i = 0 ; i != len ; i++) {
[res appendFormat:#"%i ", p[i]];
}
[res appendString:#"]"];
return res;
}
#end
Now you can use this to NSLog strings in the new format:
NSLog("Data:%#", [myData asDecimalString]);

Related

How to convert HEX to NSString in Objective-C j?

I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?
- (NSMutableString *) hextostring:(NSString *) str{
//ت
NSMutableString *string = [[NSMutableString alloc]init];
str = [str stringByReplacingOccurrencesOfString:#"&#" withString:#"0"];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"z;"];
NSArray *arr = [str componentsSeparatedByString:#";"];
for (int i =0; i<[arr count]; i++) {
if ([[arr objectAtIndex:i] isEqualToString:#"z"]) {
[string appendString:#" "];
} else {
unsigned x;
[[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
[string appendFormat:#"%C",(unichar)x];
}
}
NSLog(#"%#",string);
return string;
}
Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
NSString *nospaces = [raw stringByReplacingOccurrencesOfString:#" " withString:#""]; // one way to remove the spaces
const char *cString = [nospaces UTF8String]; // C string
NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
NSString *decoded = attributed.string; // and finally as plain text
return decoded;
}
That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = #"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(#"%# -> %#", raw, decoded);
HTH

How to get a certain bytes length subString from a NSString

Such as I have a NSString is str = #"我就是测试一下" or str = #"我" . And I want to restrict a certain byte length. such as byteLength = 10.
I know the subSrtring is not the str.length=10 How to get a certain bytes length subString from a NSString, thank you
you can use dataUsingEncoding method to get a NSData from NSString. And then use length and bytes property to get the byte length or bytes
Then if the NSData's length > your certain length you should use + (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length; method to get the certain length byte NSData you should be careful that the return NSData may be can not decode by NSString
At last you can use - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; method to get the result NSString you want
And you can use the code below:
- (NSString *)fetchStringWithOriginalString:(NSString *)originalString withByteLength:(NSUInteger)length
{
NSData* originalData=[originalString dataUsingEncoding:NSUTF8StringEncoding];
const char *originalBytes = originalData.bytes;
//make sure to use a loop to get a not nil string.
//because your certain length data may be not decode by NSString
for (NSUInteger i = length; i > 0; i--) {
#autoreleasepool {
NSData *data = [NSData dataWithBytes:originalBytes length:i];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (string) {
return string;
}
}
}
return #"";
}
you can call the above method like this :
NSString* originalString= #"我就是测试一下";
NSString *string = [self fetchStringWithOriginalString:originalString withByteLength:10];
NSData* stringData=[string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"10 bytes string : %# ; it only %i bytes",string,stringData.length);
The Result :
Be careful:
the - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; may be return nil
As apple said:the - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; Return:
An NSString object initialized by converting the bytes in data into
Unicode characters using encoding. The returned object may be
different from the original receiver. Returns nil if the
initialization fails for some reason (for example if data does not
represent valid data for encoding).
So you should use a for loop to get a nearest length data which can decode by NSSting
Use
[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]
I think this should work:
NSUInteger bytes = [incomingText lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if (bytes > MAX_TEXT_BYTES) {
int length = [incomingText length];
int cutoffIndex = (int)(MAX_TEXT_BYTES * (length / bytes));
return [incomingText substringToIndex:cutoffIndex];
}

Shuffling a greek word in iOS prints unknown symbols

I want to shuffle a string that contains Greek characters:
Here is my code:
- (void)shuffle {
NSLog(#"Will shuffle :%#",anagram2);
NSData* data = [anagram2 dataUsingEncoding:NSWindowsCP1253StringEncoding];
NSLog(#"after encoding :%#",anagram2);
NSString *someString = [[NSString alloc]initWithData:data encoding:NSWindowsCP1253StringEncoding];
NSLog(#"Greek word:%#",someString);
int length = anagram2.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
NSLog(#"Character:%#",letter);
[letters addObject:someLetter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
//NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
}
I can see the Greek word correctly. But the shuffling does not work. How can I extract each character and add it to a letters array. It works with English words but not with Greek ones, so I suppose that I should replace this:
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
with something else.
The main problem seems to me that
[NSString stringWithFormat:#"%c":...]
works only with ASCII characters. You would have to use at least the "%C" format to make
it work with Unicode characters.
Also the conversion from NSString to NSData and back would fail as soon as you have any characters that are not available in the specified encoding.
The following method avoids all these problems and should work with arbitrary Unicode characters
(even with Emojis, which are internally represented as 2 UTF-16 characters):
NSString *string = #"Ελλάδα 😄";
NSLog(#"Will shuffle: %#", string);
// Convert string to an array of (32 bit) Unicode characters:
NSMutableData *data = [[string dataUsingEncoding:NSUTF32BigEndianStringEncoding] mutableCopy];
uint32_t *letters = [data mutableBytes];
int length = [data length]/4; // The number of 32-bit Unicode characters
// Shuffle the Unicode characters:
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
uint32_t tmp = letters[i];
letters[i] = letters[value];
letters[value] = tmp;
}
// Create new string from the shuffled Unicode characters:
NSString *shuffled = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding];
NSLog(#"Shuffled: %#", shuffled);
Output:
Will shuffle: Ελλάδα 😄
Shuffled: α😄άλλ Εδ

How convert string utf-8?

i've an NSString like this:
NSString *word = #"119,111,114,100"
So, what i want to do is to convert this NSString to word
So the question is, in which way can i convert a string to a word?
// I have added some values to your sample input :-)
NSString *word = #"119,111,114,100,32,240,159,145,141";
// Separate components into array:
NSArray *array = [word componentsSeparatedByString:#","];
// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
bytes[i] = [array[i] intValue];
}
// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
Output:
word 👍
Try this:
NSString *word = #"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:#","];
for (NSString *string in array) {
char character=[string integerValue];
NSLog(#"%c",character);
}
Output:
w
o
r
d
libicu it's an UTF8 library that supports a conversion from an array of bytes as stated here.
The thing is, it offers Java, C or C++ APIs, not obj-c.

How to convert NData populated with hex values to NSString

I have a NSdata object that is populated with a bunch of information thats formated in hex.. I am trying to convert it into its proper string representation but am struggling to have any success.
One thing I have tried is to simply put it into a NSString and then NSLog it with a special character identifier thingy.. forgot the word (%02x), However to do this I am encoding it to NSUTF16.. which i dont want to do.. I mearly want to see exactly whats the data I am getting looks like as a NSString.
The reason I am doing this is because I am having some issues with my encoding later on in my code and im not sure if its because the data I am receiving is incorrect or me stuffing it up at some point when I am handling it.
Any help would be appreciated.
You can get a string representation of your NSData like so:
NSData *data = (your data)
NSString *string = [NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];
Does that answer your question?
Maybe I haven't understood, but something like this:
NSData *yourData;
NSLog(#"%#", [yourData description]);
doesn't fit your need?
Give this a try -
-(NSString*)hexToString:(NSData*)data{
NSString *hexString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%d", decimalValue];
}
return string;
}

Resources