i have string representing data .i need to convert those data to the hex array .By using the hex array data i can pass it to the CRC for writing to the peripheral
M
Byte[]
class is an array of characters. I mean you can only set one character at it's index.
If we have
Byte comm[24];
then comm[0]=0x01;
is looks like confusing here because it only saves one character.
And the statement will be like comm[0]='x';
.
Below code will creates Byte[]
from given string.
NSString *stringsdata=@"helloworld1234567812345q";
CFStringRef cfString = (__bridge CFStringRef)stringsdata;
char *array = charArrayFromCFStringRef(cfString);
size_t length= strlen(array);
Byte comm[24];
for (int i = 0; i < length; i++) {
comm[i] = array[i];
}
Conversion function:
char * charArrayFromCFStringRef(CFStringRef stringRef) {
if (stringRef == NULL) {
return NULL;
}
CFIndex length = CFStringGetLength(stringRef);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
char *buffer = (char *)malloc(maxSize);
if (CFStringGetCString(stringRef, buffer, maxSize, kCFStringEncodingUTF8)) {
return buffer;
}
return NULL;
}
OutPut:
Printing description of comm:
(Byte [24]) comm = {
[0] = 'h'
[1] = 'e'
[2] = 'l'
[3] = 'l'
[4] = 'o'
[5] = 'w'
[6] = 'o'
[7] = 'r'
[8] = 'l'
[9] = 'd'
[10] = '1'
[11] = '2'
[12] = '3'
[13] = '4'
[14] = '5'
[15] = '6'
[16] = '7'
[17] = '8'
[18] = '1'
[19] = '2'
[20] = '3'
[21] = '4'
[22] = '5'
[23] = 'q'
}
The thing here is if you still convert any character from Byte[]
then you can only save one character at any index.
Because for above characters it's hex value is more than one character and you can only save one character in Byte[]
.
I suggest to use NSArray
to save each character's hex value in NSString
format.