-1

I have NSString "3265" and i have to send this to a method in function in '.c' file has a parameter unsigned short

here my code..

In .c file

bool checkData(unsigned short num) {

}

In .swift file

var number: NSString! = "3265"

i need to send '0x3265' to checkData function.

How can i convert 3265(NSString) to 0x3265(unsigned short)

iosLearner
  • 1,312
  • 1
  • 16
  • 30

3 Answers3

0

This should work:

// This number is hex, not decimal (although it looks decimal)
let str = "3265"
// Hence we must parse it as a base-16 number:
let num : CUnsignedShort = CUnsignedShort(strtoul(str, nil, 16))
// Convert it back to hex for printing
println(String(num, radix:16)) // This should produce 3265

The call of strtoul converts the string to a number, interpreting it as hex. Then you make an CUnsignedShort from it, which you can pass to your C function.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
NSString *numberString = @"42";
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *number = [numberFormatter numberFromString:numberString];
short numberShort = [number shortValue];
Nick Wilkerson
  • 353
  • 2
  • 17
-1

You can use NSScanner to convert NSString hexadecimals into ints:

int myVal;
NSScanner *scanner = [NSScanner scannerWithString:number];
[scanner scanHexInt:&myVal];
bool myBool = scanData((unsigned short)myVal);

Obviously this is objective-c but you should be able to do this in swift no problems.

It might be an idea to set myVal to -1 and then check that it is >= 0 before sending it to the scanData() function to make sure no errors have occurred.

See this SO question.

Community
  • 1
  • 1
Rob Sanders
  • 5,197
  • 3
  • 31
  • 58
  • You are passing the address of an `unsigned short` to a function expecting the address of an `int`. This can cause a crash or any kind of undefined behavior. – Martin R Feb 05 '15 at 12:32