我想将 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/