NSData to NSString returns Null

前端 未结 3 1610
-上瘾入骨i
-上瘾入骨i 2021-01-08 00:27

I have searched. But still couldnt get it.

I\'m converting NSdata to NSString. When I do [data description]; it returns me <00000000 31323334 353637

相关标签:
3条回答
  • 2021-01-08 00:48

    I'm converting NSdata to NSString. When I do [data description]; it returns me <00000000 31323334 35363738> Yes, Im receiving my string @"12345678".

    No -- you aren't receiving that string. You are receiving a byte sequence that starts with a bunch of 0x00 values and is followed by a series of bytes that happen to correspond to the ASCII sequence "12345678".

    I.e. you have raw data and are trying to convert it to a constrained type, but can't because the constrained type cannot represent the raw data.

    You could try using the "lossy conversion" APIs on NSString, but that might not work and would be fragile anyway.

    Best bet?

    Only convert the bytes in the NSData that actually represent the string to an instance of NSString. That can be done with -initWithBytes:length:encoding:; you'll need to do the calculations to find the correct offset and length.

    0 讨论(0)
  • 2021-01-08 00:55

    This may be because the first bytes of your data is 00. The character 0 is the end of string character. When creating a string from ASCII (from an array of chars or an array of bytes as you are doing), when the character 0 is encountered at the beginning, it produces an empty string.

    I would however expect it to return an instance of NSString with 0 characters, and not null.

    0 讨论(0)
  • 2021-01-08 01:03

    This happens if the encoding is incorrect.

    Try using ASCII to test out. ASCII almost certainly work to retrive somekind of string. If it's only numbers it will probably work.

    NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding];
    

    Most common except UTF-8 enconding is:

    NSASCIIStringEncoding
    NSUnicodeStringEncoding
    NSISOLatin1StringEncoding
    NSISOLatin2StringEncoding
    NSSymbolStringEncoding
    

    try them out and see if they work.

    0 讨论(0)
提交回复
热议问题