`
xurichusheng
  • 浏览: 341762 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

【转】一个比较快的Base64 编码/解码 算法

 
阅读更多

 

转自: 中国开源社区  最快的 Base64 编码/解码 算法

 

需要的jar包  commons-lang-2.5.jar

 

import java.util.Arrays;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.time.StopWatch;

public class Base64 {
	private static final char[] CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
			.toCharArray();

	private static final int[] INV = new int[256];

	static {

		Arrays.fill(INV, -1);

		for (int i = 0, iS = CHARS.length; i < iS; i++) {

			INV[CHARS[i]] = i;

		}

		INV['='] = 0;

	}

	/**
	 * 
	 * Returns Base64 characters, a clone of used array.
	 */

	public static char[] getAlphabet() {

		return CHARS.clone();

	}

	// ---------------------------------------------------------------- char[]

	public static char[] encodeToChar(String s) {

		try {

			return encodeToChar(s.getBytes("UTF-8"), false);

		} catch (UnsupportedEncodingException ignore) {

			return null;

		}

	}

	public static char[] encodeToChar(byte[] arr) {

		return encodeToChar(arr, false);

	}

	/**
	 * 
	 * Encodes a raw byte array into a BASE64 <code>char[]</code>.
	 */

	public static char[] encodeToChar(byte[] arr, boolean lineSeparator) {

		int len = arr != null ? arr.length : 0;

		if (len == 0) {

			return new char[0];

		}

		int evenlen = (len / 3) * 3;

		int cnt = ((len - 1) / 3 + 1) << 2;

		int destLen = cnt + (lineSeparator ? (cnt - 1) / 76 << 1 : 0);

		char[] dest = new char[destLen];

		for (int s = 0, d = 0, cc = 0; s < evenlen;) {

			int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8

			| (arr[s++] & 0xff);

			dest[d++] = CHARS[(i >>> 18) & 0x3f];

			dest[d++] = CHARS[(i >>> 12) & 0x3f];

			dest[d++] = CHARS[(i >>> 6) & 0x3f];

			dest[d++] = CHARS[i & 0x3f];

			if (lineSeparator && (++cc == 19) && (d < (destLen - 2))) {

				dest[d++] = '\r';

				dest[d++] = '\n';

				cc = 0;

			}

		}

		int left = len - evenlen; // 0 - 2.

		if (left > 0) {

			int i = ((arr[evenlen] & 0xff) << 10)

			| (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);

			dest[destLen - 4] = CHARS[i >> 12];

			dest[destLen - 3] = CHARS[(i >>> 6) & 0x3f];

			dest[destLen - 2] = left == 2 ? CHARS[i & 0x3f] : '=';

			dest[destLen - 1] = '=';

		}

		return dest;

	}

	/**
	 * 
	 * Decodes a BASE64 encoded char array.
	 */

	public byte[] decode(char[] arr) {

		int length = arr.length;

		if (length == 0) {

			return new byte[0];

		}

		int sndx = 0, endx = length - 1;

		int pad = arr[endx] == '=' ? (arr[endx - 1] == '=' ? 2 : 1) : 0;

		int cnt = endx - sndx + 1;

		int sepCnt = length > 76 ? (arr[76] == '\r' ? cnt / 78 : 0) << 1 : 0;

		int len = ((cnt - sepCnt) * 6 >> 3) - pad;

		byte[] dest = new byte[len];

		int d = 0;

		for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {

			int i = INV[arr[sndx++]] << 18 | INV[arr[sndx++]] << 12

			| INV[arr[sndx++]] << 6 | INV[arr[sndx++]];

			dest[d++] = (byte) (i >> 16);

			dest[d++] = (byte) (i >> 8);

			dest[d++] = (byte) i;

			if (sepCnt > 0 && ++cc == 19) {

				sndx += 2;

				cc = 0;

			}

		}

		if (d < len) {

			int i = 0;

			for (int j = 0; sndx <= endx - pad; j++) {

				i |= INV[arr[sndx++]] << (18 - j * 6);

			}

			for (int r = 16; d < len; r -= 8) {

				dest[d++] = (byte) (i >> r);

			}

		}

		return dest;

	}

	// ---------------------------------------------------------------- byte

	public static byte[] encodeToByte(String s) {

		try {

			return encodeToByte(s.getBytes("UTF-8"), false);

		} catch (UnsupportedEncodingException ignore) {

			return null;

		}

	}

	public static byte[] encodeToByte(byte[] arr) {

		return encodeToByte(arr, false);

	}

	/**
	 * 
	 * Encodes a raw byte array into a BASE64 <code>byte[]</code>.
	 */

	public static byte[] encodeToByte(byte[] arr, boolean lineSep) {

		int len = arr != null ? arr.length : 0;

		if (len == 0) {

			return new byte[0];

		}

		int evenlen = (len / 3) * 3;

		int cnt = ((len - 1) / 3 + 1) << 2;

		int destlen = cnt + (lineSep ? (cnt - 1) / 76 << 1 : 0);

		byte[] dest = new byte[destlen];

		for (int s = 0, d = 0, cc = 0; s < evenlen;) {

			int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8

			| (arr[s++] & 0xff);

			dest[d++] = (byte) CHARS[(i >>> 18) & 0x3f];

			dest[d++] = (byte) CHARS[(i >>> 12) & 0x3f];

			dest[d++] = (byte) CHARS[(i >>> 6) & 0x3f];

			dest[d++] = (byte) CHARS[i & 0x3f];

			if (lineSep && ++cc == 19 && d < destlen - 2) {

				dest[d++] = '\r';

				dest[d++] = '\n';

				cc = 0;

			}

		}

		int left = len - evenlen;

		if (left > 0) {

			int i = ((arr[evenlen] & 0xff) << 10)

			| (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);

			dest[destlen - 4] = (byte) CHARS[i >> 12];

			dest[destlen - 3] = (byte) CHARS[(i >>> 6) & 0x3f];

			dest[destlen - 2] = left == 2 ? (byte) CHARS[i & 0x3f] : (byte) '=';

			dest[destlen - 1] = '=';

		}

		return dest;

	}

	/**
	 * 
	 * Decodes a BASE64 encoded byte array.
	 */

	public static byte[] decode(byte[] arr) {

		int length = arr.length;

		if (length == 0) {

			return new byte[0];

		}

		int sndx = 0, endx = length - 1;

		int pad = arr[endx] == '=' ? (arr[endx - 1] == '=' ? 2 : 1) : 0;

		int cnt = endx - sndx + 1;

		int sepCnt = length > 76 ? (arr[76] == '\r' ? cnt / 78 : 0) << 1 : 0;

		int len = ((cnt - sepCnt) * 6 >> 3) - pad;

		byte[] dest = new byte[len];

		int d = 0;

		for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {

			int i = INV[arr[sndx++]] << 18 | INV[arr[sndx++]] << 12

			| INV[arr[sndx++]] << 6 | INV[arr[sndx++]];

			dest[d++] = (byte) (i >> 16);

			dest[d++] = (byte) (i >> 8);

			dest[d++] = (byte) i;

			if (sepCnt > 0 && ++cc == 19) {

				sndx += 2;

				cc = 0;

			}

		}

		if (d < len) {

			int i = 0;

			for (int j = 0; sndx <= endx - pad; j++) {

				i |= INV[arr[sndx++]] << (18 - j * 6);

			}

			for (int r = 16; d < len; r -= 8) {

				dest[d++] = (byte) (i >> r);

			}

		}

		return dest;

	}

	// ---------------------------------------------------------------- string

	public static String encodeToString(String s) {

		try {

			return new String(encodeToChar(s.getBytes("UTF-8"), false));

		} catch (UnsupportedEncodingException ignore) {

			return null;

		}

	}

	public static String decodeToString(String s) {

		try {

			return new String(decode(s), "UTF-8");

		} catch (UnsupportedEncodingException ignore) {

			return null;

		}

	}

	public static String encodeToString(byte[] arr) {

		return new String(encodeToChar(arr, false));

	}

	/**
	 * 
	 * Encodes a raw byte array into a BASE64 <code>String</code>.
	 */

	public static String encodeToString(byte[] arr, boolean lineSep) {

		return new String(encodeToChar(arr, lineSep));

	}

	/**
	 * 
	 * Decodes a BASE64 encoded string.
	 */

	public static byte[] decode(String s) {

		int length = s.length();

		if (length == 0) {

			return new byte[0];

		}

		int sndx = 0, endx = length - 1;

		int pad = s.charAt(endx) == '=' ? (s.charAt(endx - 1) == '=' ? 2 : 1)

		: 0;

		int cnt = endx - sndx + 1;

		int sepCnt = length > 76 ? (s.charAt(76) == '\r' ? cnt / 78 : 0) << 1

		: 0;

		int len = ((cnt - sepCnt) * 6 >> 3) - pad;

		byte[] dest = new byte[len];

		int d = 0;

		for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {

			int i = INV[s.charAt(sndx++)] << 18 | INV[s.charAt(sndx++)] << 12

			| INV[s.charAt(sndx++)] << 6 | INV[s.charAt(sndx++)];

			dest[d++] = (byte) (i >> 16);

			dest[d++] = (byte) (i >> 8);

			dest[d++] = (byte) i;

			if (sepCnt > 0 && ++cc == 19) {

				sndx += 2;

				cc = 0;

			}

		}

		if (d < len) {

			int i = 0;

			for (int j = 0; sndx <= endx - pad; j++) {

				i |= INV[s.charAt(sndx++)] << (18 - j * 6);

			}

			for (int r = 16; d < len; r -= 8) {

				dest[d++] = (byte) (i >> r);

			}

		}

		return dest;

	}

	public static void main(String[] args) {

		StopWatch sw = new StopWatch();
		sw.start();

		String str = "!@#¥%……&*()——+brown fox jumps 你好,我是谁,Hello,我dogThe quick brown fox jumps over the lazy dog";

		for (int i = 0; i < 100000; i++) {
			//Base64.encodeToByte(str);
			Base64.encodeToString(str);
		}

		//System.out.println(Base64.encodeToString(str));

		sw.stop();

		System.out.println(sw.getTime() + "毫秒");

	}

}

 

 

分享到:
评论

相关推荐

    labview 图片缩放 base64编码base64解码

    通常,你需要选择一个原始图像,然后指定新的尺寸,LabVIEW会使用插值算法(如最近邻或双线性插值)来保持图像质量。通过这种方法,你可以将大图片缩小,或者将小图片放大以适应不同的显示或存储需求。 2. **Base64...

    base64 编码与解码 中文完美支持

    在提到的"目前速度最快、效率最高",可能是指这个Base64工具采用了优化的算法,减少了不必要的计算和内存操作,提高了编码和解码的速度,这对于处理大量数据的场景尤其重要。 提供的两个文件,`Base64.java`很可能...

    Base64编码解码工具成品+源码

    在本压缩包中,包含了一个名为"Base64编码解码.e"的易语言源码文件和一个编译好的可执行文件"Base64解码工具.exe"。易语言是一种简洁明了的中文编程语言,旨在让普通用户也能轻松进行程序开发。使用易语言编写Base64...

    QT图片BAse64编码与解码

    QT框架,由Trolltech(现为Digia)开发,是一个跨平台的C++库,提供了丰富的功能,包括图形用户界面、网络通信、多媒体处理等,对于Base64编码和解码也提供了便捷的支持。 在QT中,我们可以利用QByteArray类和...

    base64编码解码器

    这个"base64编码解码器"是一个工具,能够对文件进行Base64编码和解码操作,方便用户处理二进制数据。 1. **Base64编码原理** - Base64编码源于ASCII字符集,使用了64个字符来表示二进制数据,这64个字符包括大小写...

    BASE64编码解码_ASM(高性能汇编版)

     2) 修复 BASE64编码解码,个别情况下不会选择AVX2模式的问题(C/C++的bool类型是单字节,易的逻辑型是4字节,易的逻辑型为真时 转为字节集可能是{0,0,1,0},导致单字节判断 时灵时不灵)。1.4更新(2019.6.5)。 1) 添加...

    易语言 base64编码转图片 如何 提高转换速度.zip

    在IT行业中,Base64编码是一种常见的数据编码方式,它将二进制数据转化为可打印的ASCII字符,常用于在网络上传输图片、音频或视频等非文本数据。易语言作为一款中国本土化的编程语言,提供了处理Base64编码的功能。...

    自己实现的Base64编码和解码,支持自定义字母表

    自己用java实现的Base64编码和解码,支持自定义字母表,文章地址http://blog.csdn.net/zzhouqianq/article/details/46992347

    js对图片base64编码字符串进行解码并输出图像示例

    需要注意的是,这段代码没有提供完整的Base64解码逻辑,实际的`decodeBase64`函数需要实现Base64编码的解码算法,这通常涉及到将Base64字符映射回它们代表的二进制值。 总的来说,这个示例展示了JavaScript在处理二...

    base64解码编码优化算法及实现

    ### Base64编码与解码优化算法详解 #### 一、Base64编码的基本原理 Base64是一种常用的二进制到文本字符串的编码方法,主要用于在不支持二进制数据传输的应用层协议中安全地传输二进制数据。Base64编码的主要目标...

    Base64编码 解码 C++

    Base64编码基于一个简单的算法:将每3个字节(24位)的数据分割成4个6位的块。每个6位块可以表示从0到63的数字,这个数字对应于64个可能的ASCII字符之一。这64个字符包括大小写字母(A-Z,a-z)、数字(0-9)以及"+...

    java实现BASE64编码和解码程序

    实现BASE64编码和解码程序, 在类中实现如下函数并运行测试正确。 BASE64编码算法请在网上查询。 public String encode(byte[] data) { } public byte[] decode(String b) { }

    Base64码的编码与解码

    在实现Base64编码和解码算法时,开发者通常会使用预定义的查表方法,即创建一个包含64个Base64字符的数组,用于编码时的查找和解码时的映射。此外,现代编程语言通常内置了Base64编码和解码的库函数,如Python的`...

    c++图片与base64互转

    - 编码完成后,将Base64字符串存储到一个`std::string`对象中。 2. **从Base64到图片**: - 解码Base64字符串得到原始的二进制数据,同样可以使用第三方库或自定义函数完成。 - 将解码后的二进制数据转换回`cv::...

    Java基于Base64实现编码解码图片文件

    "Java基于Base64实现编码解码图片文件" Java基于Base64实现编码解码图片文件是Java语言中的一种常见的编码解码实现方式。Base64是一种常用的字符编码,在很多地方都会用到,但它并不是安全领域下的加密解密算法,...

    base64编码解码c文件

    学习和理解这些资源,你可以深入掌握Base64编码解码的基本概念,编写自己的C语言实现,同时通过流程图加深对算法流程的理解。在实际应用中,Base64编码常用于数据加密、邮件附件、JSON Web Tokens (JWT) 等场景。...

    Base64编码解码器

    在“云守护版Base64编码解码器”中,它基于开源加密库OpenSSL实现,提供了对Base64编码和解码的功能。 OpenSSL是一个强大的安全套接层(SSL)和传输层安全(TLS)协议实现,同时也包含各种常用的加密算法、证书工具...

    base64编码解码工具源码

    在这个“base64编码解码工具源码”中,我们可以期待找到一个实现了Base64编码和解码功能的应用程序。这个工具具有用户界面,使得非技术用户也能方便地对数据进行编码和解码操作。用户界面可能包含输入框用于输入待...

    基于JavaScript的轻量化BASE64编码及解码算法.pdf

    基于JavaScript的轻量化BASE64编码及解码算法.pdf

    base64 编码解码小工具,需要.net4.8支持

    这个“base64 编码解码小工具”是一个本地应用程序,依赖于.NET Framework 4.8运行环境,它提供了方便的功能,帮助用户快速对字符串进行Base64编码和解码。 首先,我们要理解什么是.NET Framework。这是一个由微软...

Global site tag (gtag.js) - Google Analytics