1

我想将 NSString 转换为字节数组。这就是我在 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],但它基本上返回相同的字符串。我需要类似上面的代码。

4

3 回答 3

1

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

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;
}
于 2013-09-19T16:13:26.213 回答
0

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

  • (const char *)UTF8String

您可以在此处找到文档:

NSString 文档

于 2013-09-19T15:50:03.303 回答
0

您可能想花一点时间了解字符编码,以免这不是巫术魔法。;-)

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

于 2013-09-19T16:17:13.957 回答