Friday 18 October 2013

Convert Base64 to Bytes and convert Bytes to String

import java.io.IOException;

import sun.misc.BASE64Decoder;

public class ConvertorFactory {
    public ConvertorFactory() {
        super();
    }
   

public static void main(String[] args) {


       
            try {  

           String someBase64String = "<paste base64 coded string here>";
           BASE64Decoder decoder = new BASE64Decoder();
            byte[] byte= decoder.decodeBuffer(someBase64String);
   
            ConvertorFactory enc = new ConvertorFactory();
            String myMessage = enc.bytesToStringUTFCustom(byte);
            System.out.println("myDecodedString: " +myMessage);

           
        } catch (IOException e) {
        }
    }



    public static String bytesToStringUTFCustom(byte[] bytes) {
        char[] buffer = new char[bytes.length >> 1];
        for (int i = 0; i < buffer.length; i++) {
            int bpos = i << 1;
            char c = (char)(((bytes[bpos] & 0x00FF) << 8) + (bytes[bpos + 1] & 0x00FF));
            buffer[i] = c;
        }
        return new String(buffer);

    }

No comments:

Post a Comment