I am not sure the equivalent of mutableData in Java. and the Java function to convert raw data into ASCII encoded strin开发者_如何学编程g.
+ (NSString*) encode:(const uint8_t*) input length:(NSInteger) length {
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
return [[[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding] autorelease];
}
java.lang.String has a constructor that takes a byte array and a character encoding (you could use US-ASCII
)
NSData
, and its mutable variant NSMutableData
are just object-oriented wrappers for byte buffers.
In Java, this is usually just a byte[]
.
The NSASCIIStringEncoding
, if I understand it correctly, is just an encoding that converts an 8-bit UTF-8 string and encodes it in a 7-bit clean ASCII encoding. (Which may be a lossy transformation). The equivalent of this would be to supply US-ASCII
as an encoding to the constructor for String
. I think the constructor you want is String(byte[] bytes, String charsetName)
The interesting thing about how your NSMutableData is being created is the length that they specify: ((length + 2) / 3) * 4
This suggests to me that NSASCIIStringEncoding
might be doing a Base64 encoding to do the 8-bit to 7-bit transformation. If that's the case, then the transformation isn't lossy after all. The equivalent in Java would be something like the Base64 utility in Apache Commons.
Edit: On second thought, and after some searching, I don't think that NSASCIIStringEncoding
is doing any Base64 encoding, but that it may introduce escape codes for characters that are not 7-bit clean, and the above length is just their calculated worst case for the length that might be needed if every character needs to be escaped. So I don't think you would need the apache commons library at all: just a byte[]
and the aforementioned String constructor.
精彩评论