1

I have an 8 bit Hex Value like: "FB" (-5). Now I need an signed integer value for this hex. The NSScanner don't work on this place, because you need an 4 Byte hex value, to get it negative. Before I start some bit manipulation, maybe someone of you know the better way to do that?

Watsche
  • 438
  • 2
  • 13

1 Answers1

3

Type casting is not safe but you really need it.

NSString *tempNumber = @"FB";
NSScanner *scanner = [NSScanner scannerWithString:tempNumber];
unsigned int temp;
[scanner scanHexInt:&temp];
int actualInt = (char)temp; //why char because you have 8 bit integer
NSLog(@"%@:%d:%d",tempNumber, temp, actualInt);

Console output: FB:251:-5

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
  • One more thing. I also have an 16 bit Int, that also can be negativ. How to do that in this case? Cast would not work anymore? – Watsche Aug 26 '14 at 14:14
  • Maybe I really need to go the other way and negate the value and then increment 1 and such a stuff? – Watsche Aug 26 '14 at 14:16
  • 1
    For `16 bit` integer you can cast it to `short int` which is '16 bit` (tested on 32 bit simulator and 64 bit simulator). Although the size of `short int` depends upon the compiler implementation. In general it's `short int <= int <= long int` – Inder Kumar Rathore Aug 26 '14 at 16:06