how to convert byte value into int in objective-c

独自空忆成欢 提交于 2019-12-18 18:05:10

问题


Please tell me how to convert bytes to NSInteger/int in objective-c in iPhone programming?


回答1:


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.




回答2:


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;



回答3:


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.




回答4:


NSInteger x = 3;
unsigned char y = x;
int z = x + y;



回答5:


Use the "=" operator.



来源:https://stackoverflow.com/questions/2718712/how-to-convert-byte-value-into-int-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!