0

How to convert Char array to long in obj c

 unsigned char *composite[4]; 
composite[0]=spIndex;
composite[1]= minor;
composite[2]=shortss[0];
composite[3]=shortss[1];

i need to convert this to Long int..Anyone please help

012346
  • 199
  • 1
  • 4
  • 23
  • So you want those 4 strings concatenated and then converted to an integer? Or did you perhaps mean `unsigned char composite[4]` instead? – trojanfoe Sep 24 '12 at 06:42
  • i am trying to do something similar to this `(new BigInteger(1,composite))` which is in java code – 012346 Sep 24 '12 at 06:55
  • In java byte array composite value is [1, 9, 0, 10] and BigInteger comp = new BigInteger(1,composite); this gives 17367050 value i am not getting this value.my composite value is [0] 0x00000001,[1]0x0000005a,[2]0x00000000,[3]0x0000000a – 012346 Sep 24 '12 at 07:11
  • And how do you hope to hold this value once you've converted it (given it's 128-bit)? You will need to implement your own version of `BigInteger` and this conversion is just one small part of that implementation. – trojanfoe Sep 24 '12 at 07:59
  • Please check these links maybe they will be of help :) http://stackoverflow.com/questions/169925/how-to-do-string-conversions-in-objective-c http://stackoverflow.com/questions/3609972/converting-int-double-to-char-array-in-c-or-objective-c – IronManGill Sep 24 '12 at 06:38

1 Answers1

0

If you are looking at converting what is essentially already a binary number then a simple type cast would suffice but you would need to reverse the indexes to get the same result as you would in Java: long value = *((long*)composite);

You might also consider this if you have many such scenarios:

union {
  unsigned char asChars[4];
  long asLong;
} value;

value.asChar[3] = 1;
value.asChar[2] = 9;
value.asChar[1] = 0;
value.asChar[0] = 10;

// Outputs 17367050
NSLog(@"Value as long  %ld",value.asLong);
aLevelOfIndirection
  • 3,522
  • 14
  • 18