Andrew Bullock
Andrew Bullock

Reputation: 37398

iOS objective C: convert utf-16 to base64

How can I read a string from a text input in objective C (iOS SDK), and treating it as UTF-16, encode the bytes to base64?

I'm struggling with both aspects, both treating the textbox's value as UTF-16 and then encoding these bytes to UTF-16.

I appreciate there are probably partial or similar questions to this on SO, I have searched (and read the various posts), but I'm an iOS/Objective C beginner and could really benefit from a complete example here.

Upvotes: 0

Views: 1011

Answers (2)

Lily Ballard
Lily Ballard

Reputation: 185741

Assuming you know how to get the value as an NSString* (which should be pretty simple), you can get UTF-16 using -getCharacters:range::

unichar *buffer = malloc(sizeof(unichar) * [str length]);
[str getCharacters:buffer range:NSMakeRange(0, [str length])];

This will give you a unichar* buffer, which is a buffer of UTF-16 characters.

Alternatively, if you prefer working with NSData*, you can use

[str dataUsingEncoding:NSUTF16StringEncoding];

Upvotes: 0

nneonneo
nneonneo

Reputation: 179552

Convert the NSString to a UTF16-encoded NSData by using

[str dataUsingEncoding:NSUTF16StringEncoding]

then convert the resulting NSData into Base64 using e.g. the answer from Converting between NSData and base64 strings.

Upvotes: 4

Related Questions