如何将NSString转换为字节数组

时间:2013-09-19 15:45:47

标签: java objective-c nsstring bytearray

我想将NSString转换为bytes数组。这就是我在Java上做的事情:

private static final String myString = ">9:2212!>3415!2345611<::156:66>12:6569;6154!<2!6!!:32!!>!943252<3:1;:>214964?6?;!?6:343564:64!93";

byte byteArr[] = toBytes(myString);

static byte[] toBytes(String s) {
        int size = s.length();
        byte bytes[] = new byte[size / 2];
        int i = 0;
        for(int j = 0; i < size; j++)
        {
            bytes[j] = (byte)((s.charAt(i) & 0xf) << 4 | s.charAt(++i) & 0xf);
            i++;
        }

        return bytes;
 }

这会让我回复:[b3k2da311

我尝试使用[myString UTF8String],但它基本上返回相同的字符串。我需要类似上面的代码。

3 个答案:

答案 0 :(得分:1)

您的代码似乎占用了字符串中每个字符的最低四位,并将它们打包到字节数组中。这对我来说似乎有点奇怪,但这是直接翻译(没有bug :))。

static NSString* const myString = @"whatever";

// In some method

// Class methods are roughly equivalent to static methods in Java
NSData* byteArray = [[self class] toBytes: myString];

// Method definition
// The result is encapsulated in a NSData to take advantage of ARC for memory management
+ (NSData*) toBytes: (NSString*) aString
{
    NSUInteger size = [aString length];
    NSMutableData bytes = [NSMutableData dataWithLength: size / 2];
    // Get a pointer to the actual array of bytes
    uint8_t* bytePtr = [bytes mutableBytes];
    NSUInteger i = 0;
    // NB your code had a bug in that an exception is thrown if size is odd
    for (NSUInteger j = 0 ; j < size / 2 ; ++j)
    {
        bytePtr[j] = (([aString characterAtIndex: i] & 0xf) << 4)
                   | ([aString characterAtIndex: i + 1] & 0xf);
       i += 2;
    }
    // NSMutableData is a subclass of NSData, so return it directly.
    return bytes;
}

答案 1 :(得分:0)

NSString有一个方法调用UTF8String,返回const char *

  • (const char *)UTF8String

您可以在此处找到文档:

NSString Documentation

答案 2 :(得分:0)

您可能希望花一点时间来理解角色编码,这样这不是巫术魔法。 ; - )

NSData* data = [theString dataWithEncoding: NSUTF16BigEndianStringEncoding]; const char* bytes = (const char*)data.bytes;