5

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

Community
  • 1
  • 1
suse
  • 10,503
  • 23
  • 79
  • 113

5 Answers5

7

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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
Vladimir
  • 7,670
  • 8
  • 28
  • 42
  • 2
    this _is_ an objective-c question. NSInteger is defined in NSObjCRuntime.h and the first #import in NSObjCRuntime.h is , so I consider the objective-c tag is ok. (Just my guess), the rationale behind this question is: someone new to objective-c may not see the difference between a NSInteger and a NSNumber at first sight. – ohho Apr 28 '10 at 06:55
  • 1
    NSInteger is a typedef, not an objective-C keyword. It's still a plain C question. – NSResponder Apr 28 '10 at 16:34
5

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;
JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • Awesome that work for me. Thanks heaps, I have been searching ages for how to do this with hex. e.g. Sing8 foo = 0xF4 converting that to an int – John Ballinger Aug 09 '11 at 02:37
4

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.

iwat
  • 3,591
  • 2
  • 20
  • 24
1
NSInteger x = 3;
unsigned char y = x;
int z = x + y;
ohho
  • 50,879
  • 75
  • 256
  • 383
  • because you got it backwards? Still not worthy of a downvote given the lack of quality of the question. – bbum Apr 27 '10 at 04:45
  • 1
    y is a byte. z is an integer. the question is "how to convert byte value into int in objective-c"... never mind. I'll get used to this... ;-) – ohho Apr 27 '10 at 04:50
-4

Use the "=" operator.

NSResponder
  • 16,861
  • 7
  • 32
  • 46
  • Can u show me with a small example? i want to knw is there any inbuilt method to convert bytes to int. – suse Apr 27 '10 at 04:27