-3

For a project I need to send a key over Bluetooth to a BLE device.

I receive the key from my webservice as a NSString. For example 1234

Now what I need to send to the device is

Byte byteArray[] = {0x12, 0x34};

Is there someone that can give me some example code of how I can do this?

Thanks

TwinsIT
  • 87
  • 1
  • 1
  • 6

2 Answers2

0

To send string as Bytes you should use the following code:

NSString *yourString = @"1234";
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

But 0x12 is hexadecimal equal to 18 in decimal.

Usefull links:

Community
  • 1
  • 1
Szu
  • 2,254
  • 1
  • 21
  • 37
  • Ok thanks. You're right with the fact that 0x12 is 18 in decimal, but in fact the 0x12 is putting the first number of the key (1) first and then the second (2). In fact it isn't a real conversion. For example: key 7823 will be 0x78 0x23. – TwinsIT Feb 19 '15 at 13:09
0

I finally managed to do this using the combination webservice - xcode Instead of sending the whole key as one string I splitted it and converted the first 2 digits to hex in PHP (on the webservice).

Using this code I created the correct byte array for sending the code:

NSString *key1 = [message objectForKey:@"key1"];
NSString *key2 = [message objectForKey:@"key2"];
unsigned char byteArray[2];
byteArray[0] = [key1 intValue];
byteArray[1] = [key2 intValue];
TwinsIT
  • 87
  • 1
  • 1
  • 6