Byte(dec)/Integer to Byte(hex) - objective-c

I have a method that converts integer to two dec Bytes:
- (void)intToBytes:(NSInteger *)integer {
int16_t i = integer;
Byte b0 = (Byte)(i / 256);
Byte b1 = (Byte)(i % 256);
NSLog(#"BYTES: %hhu, %hhu", b0, b1);
}
How could I convert those dec Bytes to hex? Or integer to hex Bytes straightaway?

Try this
NSInteger a = 449;
NSString * hex = [NSString stringWithFormat:#"%x",(unsigned int)a];
Here hex is "1c1"

Related

How to add padding to NSData so that it will be a multiple of 8 bytes?

In my code I construct a hex NSString first and then use the utility function below to convert it to NSData for transmission.
For example:
+ (NSData *)convertHexString:(NSString *)hexString {
NSString *command = [hexString stringByReplacingOccurrencesOfString:#" " withString:#""];
NSMutableData *commandToSend = [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = { '\0', '\0', '\0' };
int i;
for (i = 0; i < [command length] / 2; i++) {
byte_chars[0] = [command characterAtIndex:i * 2];
byte_chars[1] = [command characterAtIndex:i * 2 + 1];
whole_byte = strtol(byte_chars, NULL, 16);
[commandToSend appendBytes:&whole_byte length:1];
}
return commandToSend;
}
Now there is a requirement that specifies "NSData must be a minimum of 8 bytes and be a multiple of 8 bytes. NULL padding can be used to make the data a multiple length of 8 bytes." I am not sure how I can make this happen.
NSString* hexString = #"FF88";//this is two bytes right now.
//how do I add NULL padding so that it becomes 8 bytes?
Thank you!
The code below will align on 16 bytes. You could easily change it to 8 bytes as also indicated in the comments, but, depending on what you are implementing, 16 bytes might be better nowadays.
<whatever> * p;
<whatever> * p16;
// Unaligned pointer
p = malloc ( n * sizeof ( <whatever> ) + 15 ); // use 7 for 8 byte alignment
if ( p )
{
memset ( p, 0, n * sizeof ( <whatever> ) + 15 ); // 7 for 8 bytes
// 16 byte aligned pointer
p16 = ( ( uintptr_t ) p + 15 ) & ~ ( uintptr_t ) 0x0F; // 0x08 for 8 bytes
// now p16 is aligned - use as is
}
// else allocation failed handle error
Change <whatever> to taste.
PS : This is more a general pointer alignment solution, not for NSString. So you'd use it if you convert it to a char * somewhere.

iOS:CRC in obj c

i am new to iOS i need to create data packet by using CRC algorithm for the below commands
int comm[6];
comm[0]=0x01;
comm[1]=6;
comm[2]=0x70;
comm[3]=0x00;
comm[4]=0xFFFF;
comm[5]=0xFFFF;
i had a java code which as same thing developing in android
byte[] getCRC(byte[] bytes)
{
byte[] result = new byte[2];
try
{
short crc = (short) 0xFFFF;
for (int j = 0; j < bytes.length; j++)
{
byte c = bytes[j];
for (int i = 7; i >= 0; i--)
{
boolean c15 = ((crc >> 15 & 1) == 1)
boolean bit = ((c >> (7 - i) & 1) == 1);
crc <<= 1;
if (c15 ^ bit)
{
crc ^= 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
}
}
}
int crc2 = crc - 0xffff0000;
result[0] = (byte) (crc2 % 256);
result[1] = (byte) (crc2 / 256);
return result;
}
catch(Exception ex)
{
result = null;
return result;
}
}
Input for getCRC() method: The data packet for which CRC is to be calculated.
Output of getCRC() method: CRC for the packet.
The same thing i need to do in obj c please help if any sample code available also.
Objective-C also incorporates C, so the contents of your method will look almost the same as in Java. All that is needed is to pass your data into and out of the method, in this example using NSData:
- (NSData *)bytesCRCResult:(NSData *)dataBytes
{
unsigned char *result = (unsigned char *)malloc(2);
unsigned char *bytes = (unsigned char *)[dataBytes bytes]; // returns readonly pointer to the byte stream
uint16_t crc = (short) 0xFFFF;
for (int j = 0; j < dataBytes.length; j++)
{
unsigned char c = bytes[j];
for (int i = 7; i >= 0; i--)
{
bool c15 = ((crc >> 15 & 1) == 1);
bool bit = ((c >> (7 - i) & 1) == 1);
crc <<= 1;
if (c15 ^ bit)
{
crc ^= 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
}
}
}
uint16_t crc2 = crc - 0xffff0000;
result[0] = (unsigned char) (crc2 % 256);
result[1] = (unsigned char) (crc2 / 256);
NSData *resultsToData = [NSData dataWithBytes:result length:2];
free(result);
return resultsToData;
}
NSData can be read as raw bytes using the [NSData bytes] method call, and has a range of useful properties and methods.
For the boolean value, you have a few options:
"bool" seems to be the ISO C/C++ standard type
"Boolean" is defined as "typedef unsigned char"
"boolean_t" is defined as "typedef unsigned int" or "typedef int", depending on 64-bit compilation apparently
"BOOL", the Objective-C bool, which is defined as "typedef signed char", according to http://nshipster.com/bool/ and might therefore not behave as expected.
"uint8_t" can be substituted for "unsigned char", for clarity.
Please note: The above code compiles without warning or complaint, but wasn't tested with actual data.

Objective-C Raw MD5-hash

In Objective-C, I generate a simple MD5-hash of 'HelloKey', which returns 0FD16658AEE3C52060A39F4EDFB11437. Unfortunately, I could not get a raw return, so I have to work with this string to get a raw MD5-hash (or do you know how I can get a raw result from the start?)
Anyway, in order to convert it to raw, I split it into chunks of 2 chars each, calculate the hex value, and append a char with that value to a string.
Here's the function:
- (NSString *)hex2bin:(NSString *)input{
NSString *output = #"";
for (int i = 0; i < input.length; i+=2){
NSString *component = [input substringWithRange:NSMakeRange(i, 2)];
unsigned int outVal;
NSScanner* scanner = [NSScanner scannerWithString:component];
[scanner scanHexInt:&outVal];
/* if(outVal > 127){
outVal -= 256;
} */
// unsigned char appendage = (char)outVal;
output = [NSString stringWithFormat:#"%#%c", output, outVal];
NSLog(#"component: %# = %d", component, outVal);
}
return output;
}
When I print each outval, I get:
0F = 15
D1 = 209
66 = 102
58 = 88
AE = 174
E3 = 227
C5 = 197
20 = 32
60 = 96
A3 = 163
9F = 159
4E = 78
DF = 223
B1 = 177
14 = 20
37 = 55
However, when I print the string that I get with a special function that tells me the integer values of each character (a function which is shown here):
- (NSString *)str2bin:(NSString *)input{
NSString *output = #"";
for (NSInteger charIdx=0; charIdx < input.length; charIdx++){
char currentChar = [input characterAtIndex:charIdx];
int charNum = [NSNumber numberWithChar:currentChar].intValue;
output = [NSString stringWithFormat:#"%# %d", output, charNum];
}
return output;
}
I get: 15 20 102 88 -58 30 72 32 96 -93 -4 78 2 -79 20 55. You will notice that there are significant differences, like 209 -> 20, 174 -> -58, 227 -> 30. In some cases, the difference is 256, so no harm done. But in other cases, it's not, and I would really like to know what's going wrong. Any tips?
You are doing it wrong, since you are trying to store binary data in NSString, which is UTF8 string.
You should use NSData (or C string) to store binary hash representation.

How create a size_t and how count the size?

I create a NSData and use the function
- (const void *)bytes;
So, it return the bytes in a const void * variable. If I read the memory manually I will find this:
98 F3 00 76 84 //Then a lot of zero
Use strlen not work because the 00. But it will be aways the same size: 10 hexa lenght. So, to create a manually size_t, I will use:
size_t mysize = 0x0A
Or I have use the size in bits:
size_t mysize = 0x28
Is any of this correct?
The NSData contains the length.
const void *mybytes = [data bytes];
size_t mysize = [data length];
NSData also has -(NSUInteger)length.

how to convert byte value into int in objective-c

Please tell me how to convert bytes to NSInteger/int in objective-c in iPhone programming?
What do you mean by "Bytes"?
If you want convert single byte representing integer value to int (or NSInteger) type, just use "=":
Byte b = 123;
NSInteger x;
x = b;
as Byte (the same as unsigned char - 1 byte unsigned integer) and NSInteger (the same as int - 4 bytes signed integer) are both of simple integer types and can be converted automatically. Your should read more about "c data types" and "conversion rules".
for example http://www.exforsys.com/tutorials/c-language/c-programming-language-data-types.html
If you want to convert several bytes storing some value to int, then convertion depends on structure of these data: how many bytes per value, signed or unsigned.
If by byte, you mean an unsigned 8 bit value, the following will do.
uint8_t foo = 3; // or unsigned char foo...
NSInteger bar = (NSInteger) foo;
or even
NSInteger bar = foo;
My guess:
unsigned char data[] = { 0x00, 0x02, 0x45, 0x28 };
NSInteger intData = *((NSInteger *)data);
NSLog(#"data:%d", intData); // data:675611136
NSLog(#"data:%08x", intData); // data:28450200
So, beware of byte-order.
NSInteger x = 3;
unsigned char y = x;
int z = x + y;
Use the "=" operator.