Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting between NSData and base64 strings

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.

like image 377
aherlambang Avatar asked May 14 '11 02:05

aherlambang


People also ask

How do you convert a string to Base64?

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.

Does converting to Base64 reduce size?

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.

What is difference between ASCII and Base64?

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.

Does converting to Base64 increase size?

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.


2 Answers

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.

like image 115
Ryan Wersal Avatar answered Oct 11 '22 13:10

Ryan Wersal


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.)

like image 45
Sixten Otto Avatar answered Oct 11 '22 14:10

Sixten Otto