java - 如何将 NSString 转换为字节数组

标签 java objective-c nsstring arrays

我想将 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],但它基本上返回相同的字符串。我需要类似上面的代码。

最佳答案

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

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;
}

关于java - 如何将 NSString 转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18899292/

相关文章:

java - 瓶啤酒

objective-c - NSData initWithContentsOfURL : does not return the original allocation?

objective-c - 带有数字格式化程序的 NSTextField 不允许小数输入

java - 如何使用 JPA 以编程方式创建长度有限的 MySQL 索引?

java - 如何使用OpenCL put3DRangeKernel?

c++ - Objective-C 弧 : is it correct to use a block as C++ callback

ios - 在ios中将字符串转换为整数

iphone - 声明为 NSString 但 Xcode 视为 NSdata 并收到不兼容的传递

ios - 为什么 emoji 有两个不同的 utf-8 编码?如何从 utf-8 转换表情符号,在 ios 中使用 NSString?

java - 如何避免将 Spring Boot Fat jar 安装/部署到 Maven 仓库