What is the easiest and fastest code to do a conversion between NSData
and a base64 string? I've read a bunch of solutions at SO and mostly they involve in adding another class etc. I found a great solution here but it's too complex.
To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.
Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.
Difference between ASCII and base64When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes. When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.
This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase). The increase may be larger if the encoded data is small.
Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.
Example
NSString *originalString = [NSString stringWithFormat:@"test"]; NSData *data = [NSData dataFromBase64String:originalString]; NSLog([data base64EncodedString]);
The above will print out the original string after converting it to base64 and back to a normal unencoded string.
As of iOS 7, NSData
now directly provides this functionality with the new methods -base64EncodedDataWithOptions:
and -base64EncodedStringWithOptions:
. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With