0

I need a way to convert UInt8 array to Base64 String. I have an example in Java but I'm having trouble converting that Java code to Swift. Here is the java code:

private static String getBase64(byte[] buffer)
{
    final char[] map = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', '+', '/'
    };

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buffer.length; i++)
    {
        byte b0 = buffer[i++], b1 = 0, b2 = 0;

        int bytes = 3;
        if (i < buffer.length)
        {
            b1 = buffer[i++];
            if (i < buffer.length)
            {
                b2 = buffer[i];
            }
            else
            {
                bytes = 2;
            }
        }
        else
        {
            bytes = 1;
        }

        int total = (b0 << 16) | (b1 << 8) | b2;

        switch (bytes)
        {
            case 3:
                sb.append(map[(total >> 18) & 0x3f]);
                sb.append(map[(total >> 12) & 0x3f]);
                sb.append(map[(total >> 6) & 0x3f]);
                sb.append(map[total & 0x3f]);
                break;

            case 2:
                sb.append(map[(total >> 18) & 0x3f]);
                sb.append(map[(total >> 12) & 0x3f]);
                sb.append(map[(total >> 6) & 0x3f]);
                sb.append('=');
                break;

            case 1:
                sb.append(map[(total >> 18) & 0x3f]);
                sb.append(map[(total >> 12) & 0x3f]);
                sb.append('=');
                sb.append('=');
                break;
        }
    }

    return sb.toString();
}

Now this is what I have so far in Swift, I am having trouble with the StringBuffer and the cases in the java example:

private static func getBase64(buffer : [UInt8]) {
    let map : Array<Character> = [
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
        "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
        "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
        "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
        "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "+", "/"
    ]

    // String Buffer?

    for var i = 0; i < buffer.count; i++ {
        var b0 : UInt8 = buffer[i++]
        var b1 : UInt8 = 0
        var b2 : UInt8 = 0

        var bytes : Int = 3

        if i < buffer.count {
            b1 = buffer[i++]
            if i < buffer.count {
                b2 = buffer[i]
            } else {
                bytes = 2
            }
        } else {
            bytes = 1
        }

        let total : Int = Int((b0 << 16) | (b1 << 8) | b2)

        switch bytes
        {
        case 3:
            // not sure
            break
        case 2:
            // not sure
            break
        case 1:
            // not sure
            break
        }
    }
}

How does Swift implement a StringBuffer and how can I build out my cases like the Java code is doing in swift? Any help appreciated.

2
  • 2
    NSData has methods for conversion to and from Base64. Commented Feb 23, 2016 at 22:39
  • Do you ultimately want to convert a UTF-8 string into a Base64 string? Commented Feb 23, 2016 at 23:19

1 Answer 1

2

Assuming that what you are truly looking for is a way to convert strings to and from Base64, here's a simple way to do that:

import Foundation

extension String {
  func UTF8toBase64() -> String {
    let data = self.dataUsingEncoding(NSUTF8StringEncoding)
    return data?.base64EncodedStringWithOptions([]) ?? ""
  }

  func Base64toUTF8() -> String {
    let data = NSData.init(base64EncodedString: self, options: []) ?? NSData()
    return String(data: data, encoding: NSUTF8StringEncoding) ?? ""
  }
}

let string = "Test"
let string64 = string.UTF8toBase64() // => "VGVzdA=="
let string2 = string64.Base64toUTF8() // => "Test

This, of course, assumes UTF-8 all the way through, you might want to allow other encodings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.