uint8_t conversion to NSString - ios

I need to convert the contents of a single element in my uint8_t buffer to an NSString so that I can display it to a label on my iPhone app. I read in the contents of buffer OK from a TCP connection. I am not getting the proper encoding so that an element's value can be displayed correctly. For example, if buffer[4] has the contents of 0xFD or 253, how do I best get that transferred to the label? (The label is data1) Or is there a much simpler way? Thanks.
uint8_t buffer[64];
uint8_t tinybuffer[1];
int len;
// Read in contents from TCP connection, log dump, and display to label.
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
// Log dump
for(int i = 0; i < len; i++) {
NSLog(#"Returning byte %d : %x", i, buffer[i]);
}
NSLog(#"Finished Reading");
// Get data to the screen.
tinybuffer[0] = buffer[4];
NSString *str1 = [[NSString alloc] initWithBytes:tinybuffer length:1 encoding:NSUTF8StringEncoding];
_data1.text = str1;

NSString *str1 = [NSString stringWithFormat:#"%d", tinybuffer[0]];
should do what you want.

Related

Send hexString Data through UDP

I'm developing an iOS app. I've come across a problem.
I am trying to send a hexString data through UDP to an wifi camera, which will response while getting correct data. My code is shown below. However I can't get any response from my wifi camera. (I'm using
https://github.com/robbiehanson/CocoaAsyncSocket)
NSString *sendMsg = #"6745000005000000000000000000000000000000000000001400000067450000140000000A";
NSData *bytes = [sendMsg dataUsingEncoding:NSUTF16BigEndianStringEncoding];
NSString *host = #"255.255.255.255";
[self.udpSocket sendData:bytes toHost:host port:ListenPort withTimeout:-1 tag:1];
Beside, I've try send my data through PacketSender (an app can send UDP data), which has a correct response.
enter image description here
Problem has been solved. The problem is while converting NSString to NSData. It's hex string which need to convert to NSData. Below is my code which works.
- (NSData *)dataFromHexString:(NSString *)hexString {
NSAssert((hexString.length > 0) && (hexString.length % 2 == 0), #"hexString.length mod 2 != 0");
NSMutableData *data = [[NSMutableData alloc] init];
for (NSUInteger i=0; i<hexString.length; i+=2) {
NSRange tempRange = NSMakeRange(i, 2);
NSString *tempStr = [hexString substringWithRange:tempRange];
NSScanner *scanner = [NSScanner scannerWithString:tempStr];
unsigned int tempIntValue;
[scanner scanHexInt:&tempIntValue];
[data appendBytes:&tempIntValue length:1];
}
return data;}

How do I see the true contents of this string?

Please bear with me here since this question is not so easy to explain and word correctly.
I am using the following code in order to get data from a USB connected barcode reader, the scanner works fine and data is passed in as expected but my DB lookups fail and I believe they are failing because the data I am passing into the DBLookup method is incorrect but I am unable to see why, I think NSLog is helping me to show clear text data when in fact it isn't and I am stuck at debugging further.
Here is my code
- (void)didBarcodeDataReceive:(StarIoExtManager *)manager data:(NSData *)data {
NSLog(#"%s", __PRETTY_FUNCTION__);
NSMutableString *text = [NSMutableString stringWithString:#""];
const uint8_t *p = data.bytes;
for (int i = 0; i < data.length; i++) {
uint8_t ch = *(p + i);
[text appendFormat:#"%c", (char) ch];
}
NSLog(#"Scanned info as NSData was: %#", data); // raw NSData
//NSString *stringWithData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *stringWithData = [[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
NSLog(#"Scanned info as StringFromData was: %#", stringWithData);
NSLog(#"Scanned ch conversion is: %#", text);
int createTransactionResult = -1;
createTransactionResult = [NWBarCodeHelper createTransactionRowFromBarCode:text];
if ([NWTillHelper isDebug] == 1) {
NSLog(#"mPOP delegate holds barcode: %#", stringWithData);
if(createTransactionResult != 0) {
NSLog(#"TransactionListView:mPOPDelegate:createTransactionFrombarCode failed with errorCode %i", createTransactionResult);
}
}
}
My Debug outputs shows the correct data as follows
2017-04-19 10:19:01.868198 NWMobileTill[3751:1638657] Scanned info as NSData was: <30393235 38333834 33393439 35310d0a>
2017-04-19 10:19:01.868439 NWMobileTill[3751:1638657] Scanned info as StringFromData was: 09258384394951
2017-04-19 10:19:01.868652 NWMobileTill[3751:1638657] Scanned ch conversion is: 09258384394951
2017-04-19 10:19:01.868979 NWMobileTill[3751:1638657] NWBarCodeHelper:createTransactionRowFromBarcode:barcode = 09258384394951
2017-04-19 10:19:01.875938 NWMobileTill[3751:1638657] NWBarcodeHelper:CreateTransactionRowFromBarcode: 0 or more than one row returned, basic data error, item count = 0
But as you can see the last rows shows the DB lookup failing, I KNOW the method is correct cause when I scan using the iPhone camera and passing that data to the same method it works just fine on the same barcode so it must be something with the string that is passed in from the USB scanner that is tricking me out but I am unable to understand why and I think NSLog is trying to help me but not showing me the encoded data or something?
Your string contains a \r\n at the end. Have a look at the following code:
unsigned char bytes[] = {0x30, 0x39, 0x32, 0x35, 0x38, 0x33, 0x38, 0x34, 0x33, 0x39 ,0x34, 0x39, 0x35, 0x31, 0x0d, 0x0a};
NSData *data = [NSData dataWithBytes:bytes length:16];
NSString *stringWithData = [[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
NSLog(#"%#", stringWithData); // 09258384394951
NSLog(#"%lu", (unsigned long)[stringWithData length]); // 16
// remove \r\n at the end which gets added by the barcode scanner
NSString *string = [stringWithData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", string); // 09258384394951
NSLog(#"%lu", (unsigned long)[string length]); // 14
Or if you want to use your appendFormat approach you can just check if it is a valid digit before adding it to the string instead of removing it later.
To actually see the contents of your string you can either output the code point of each character in the string one by one or you can just set a breakpoint and Xcode will show it in the debugger:

Read integer from file IOS

I have a file that contains in the very first byte of data a number. In this case that number is 32. I have used a hex editor to confirm that (in hex) the value is "20" which equals 32 in decimal.
Can someone point me in the right direction of how to read it out of the file. I have tried about 6 different ways all of which have failed.
Lots of different ways. Here's one:
NSData *data = [NSData dataWithContentsOfFile:filename];
if ([data length] > 0)
{
const uint8_t *bytes = (const uint8_t *)[data bytes];
uint8_t byte = bytes[0];
NSLog(#"%d", byte);
}
or another:
NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:filename];
[stream open];
NSInteger bufferLen = 1;
uint8_t buffer[bufferLen];
NSInteger count = [stream read:buffer maxLength:bufferLen];
[stream close];
if (count > 0)
{
NSLog(#"%d", buffer[0]);
}

Add header information to NSData

I want to send image through iOS devices by BSD Socket.
As we know, an image is divided into several packages to be sent out, So the receiver needs the size of the image.
So I want to insert the size to the beginning of the images's binary data.
NSData* image = UIImagePNGRepresentation(screenShot);
NSUInteger len = [image length];
NSMutableData *header = [[NSMutableData alloc] initWithBytes:&len length:sizeof(NSUInteger)];
[header appendData:msg];
Receiver get the NSData and parse
NSUInteger len;
[header getBytes:&len length:sizeof(NSUInteger)]
I tried to insert int, char and NSString, but I never get the right number of the size. What's wrong with my solution?
Are there better ones?
Sender
uint32_t len = [image length];
NSLog(#"Len = %u", len);
NSMutableData *header = [NSMutableData dataWithCapacity:sizeof(len) + len];
[header appendBytes:htonl(len) length:sizeof(len)]; // use network order
[header appendData:image];
Receiver
uint32_t len;
[header getBytes:&len length:sizeof(uint32_t)];
len = ntohl(len); // network to host
printf("Len = %u\n", len);
I finally solved the problem with iOS NSData+Base64 Category http://projectswithlove.com/projects/NSData_Base64.zip

NSOutputStream not writing data properly

Using the NSStreamEventHasSpace available event, I am trying to write a simple NSString to to an NSOutputStream. Here is the contents of that event:
uint8_t *readBytes = (uint8_t *)[data mutableBytes];
readBytes += byteIndex; // instance variable to move pointer
int data_len = [data length];
unsigned int len = ((data_len - byteIndex >= 12) ?
12 : (data_len-byteIndex));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
len = [output write:(const uint8_t *)buf maxLength:len];
NSLog(#"wrote: %s", buf);
byteIndex += len;
I pretty much took it right from Apple. The data is initialized in my viewDidLoad method with
data = [NSMutableData dataWithData:[#"test message" dataUsingEncoding:NSUTF8StringEncoding]];
[data retain];
The HasSpaceAvailable event is called twice. In the first one, the entire message is written with the characters "N." appended to it. In the second time, NSLog reports that a blank message was written (not null). Then, the EndEncountered event occurs. In that event, I have
NSLog(#"event: end encountered");
assert([stream isEqual:output]);
NSData *newData = [output propertyForKey: NSStreamDataWrittenToMemoryStreamKey];
if (!newData) {
NSLog(#"No data written to memory!");
} else {
NSLog(#"finished writing: %#", newData);
}
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[stream release];
output = nil;
break;
I also got this from Apple. However, "No data written to memory!" is logged. No errors occur at anytime, and no data appears to have been received on the other end.
I seem to have fixed this by using low level Core Foundation methods instead of higher level NSStream methods. I used this article as a starting point:
http://oreilly.com/iphone/excerpts/iphone-sdk/network-programming.html
It covers input and output streams in great lenghts and has code examples.
Hope this helps.

Resources