`
eyesmore
  • 浏览: 378820 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
阅读更多

 

好些年前写的,偶然找出来,临时用下,顺便分享下~~  性能好像不咋地 

 

import java.io.ByteArrayOutputStream;

public class UltraEdit {
	public static void main(String[] args) {
		System.out.println(UltraEdit.getInstance().getHexUpperCase(" 测试 & 数据 Test Data".getBytes()));
		System.out.println(UltraEdit.getInstance().b2HEX(" 测试 & 数据 Test Data".getBytes(),":"));
		String hex = UltraEdit.getInstance().b2HEX(" 测试 & 数据 Test Data".getBytes());
		System.out.println(hex);
		System.out.println(new String(UltraEdit.getInstance().hex2b(hex)));
		
		UltraEdit.getInstance().hex2b("F");
	}
	
	
	private final static UltraEdit instance = new UltraEdit(); 
	
	private UltraEdit() {
		Configuration.byte2HexUpper = new Byte2HexUpper();
		Configuration.byte2HexLower = new Byte2HexLower();
		Configuration.byte2ASCII = new Byte2ASCII();
	}
	
	public synchronized static UltraEdit getInstance() {
		return instance;
	}
	
	public String getHexUpperCase(byte[] data) {
		return byte2HexFormat(data, 16, Configuration.byte2HexUpper,Configuration.byte2ASCII);
	}	
	
	public String getHexLowerCase(byte[] data) {
		return byte2HexFormat(data, 16, Configuration.byte2HexLower,Configuration.byte2ASCII);
	}
	
	public String getHexUpperCase(byte[] data,int width) {
		return byte2HexFormat(data, width, Configuration.byte2HexUpper,Configuration.byte2ASCII);
	}
	
	public String getHexLowerCase(byte[] data,int width) {
		return byte2HexFormat(data, width, Configuration.byte2HexLower,Configuration.byte2ASCII);
	}
	
	/** 将byte[]数据以十六进制的形式显示,显示格式仿照UltraEdit*/
	private String byte2HexFormat(byte[] data,int width,
			IByte2String hexPartitionMethod,IByte2String strPartitionMethod) 
	{
		StringBuffer sb = new StringBuffer();
		//表头
		for(int i=0;i<width;i++) {
			sb.append("-");
			if(i<10) sb.append(i);
			else sb.append((char)(i-10+'a'));
			sb.append("-");
		}
		sb.append("\r\n");
		int index = 0;
		StringBuffer hexPartionLine = new StringBuffer();
		StringBuffer strPartionLine = new StringBuffer();
		while(index < data.length) {
			int lineStart = index; 
			while(index < data.length && index < lineStart+width) {
				hexPartionLine.append(hexPartitionMethod.byte2String(data[index]))
									.append(Configuration.DELIMITER);
				strPartionLine.append(strPartitionMethod.byte2String(data[index]));
				index ++;
			}
			int placeholderNum = 0;
			while(index+placeholderNum < lineStart+width) {//对最后一行不足width的在HexPartition部分补充占位符
				hexPartionLine.append("   ");
				placeholderNum += 1;
			}
			sb.append(hexPartionLine).append(Configuration.PARTITION)
								.append(strPartionLine).append("\r\n");//完成一行显示
			hexPartionLine.delete(0, hexPartionLine.length());
			strPartionLine.delete(0, strPartionLine.length());
		}
		return sb.toString();
	}
	
	public String b2HEX(byte[] data) {
		return byte2Hex(data, "", Configuration.byte2HexUpper);
	}
	
	public String b2HEX(byte[] data,String delimiter) {
		return byte2Hex(data, delimiter, Configuration.byte2HexUpper);
	}
	
	public String b2hex(byte[] data) {
		return byte2Hex(data, "", Configuration.byte2HexLower);
	}
	
	public String b2hex(byte[] data,String delimiter) {
		return byte2Hex(data, "", Configuration.byte2HexLower);
	}
	
	private String byte2Hex(byte[] data,String delimiter,IByte2String form) {
		StringBuffer sb = new StringBuffer();
		int index = 0;
		while(index < data.length) {
			sb.append(form.byte2String(data[index])).append(delimiter);
			index ++;
		}
		return sb.toString();
	}

	public byte[] hex2b(String hexStr) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		if(hexStr.length() % 2 != 0) {
			throw new IllegalArgumentException("输入参数"+hexStr+"长度不是偶数.");
		}
		int c = 0;
		while(c < hexStr.length()) {
			int high = Configuration.hexChar2Int(hexStr.charAt(c));
			int low = Configuration.hexChar2Int(hexStr.charAt(c+1));
			if(high == -1) {
				throw new IllegalArgumentException("输入参数"+hexStr+".charAt("+c+")="+hexStr.charAt(c)+"不是合法的HexChar");
			}
			if(low == -1) {
				throw new IllegalArgumentException("输入参数"+hexStr+".charAt("+(c+1)+")="+hexStr.charAt(c+1)+"不是合法的HexChar");
			}
			baos.write(Configuration.BCDPackedFormat(high,low));
			c += 2;
		}
		return baos.toByteArray();
	}
		
	private static class Configuration {
		static final char[] HEX_UPPER_CASE = new char[]{
			'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
		};
	
		static final char[] HEX_LOWER_CASE = new char[]{
			'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
		};
		
		/**
		 * @return -1 表示输入参数hexChar不是个合法的HexChar. 其他情况返回的数据控制在[0,15]
		 * */
		static int hexChar2Int(char hexChar) {
			if(Character.isDigit(hexChar)) return hexChar - '0';
			else if(Character.isLowerCase(hexChar)) return hexChar - 'a' + 10;
			else if(Character.isUpperCase(hexChar)) return hexChar - 'A' + 10;
			else return -1;
		}
		
		static byte BCDPackedFormat(int high,int lower) {
			int min = Math.min(high, lower);
			int max = Math.max(high, lower);
			if(min<0 || max >15) {
				throw new IllegalArgumentException("输入参数"+high+","+lower+"都必须控制在范围[0,15]内");
			}
			return (byte)(high << 4 | lower);
		}
		
		/** 各个Byte之间的分割符号*/
		static final String DELIMITER = " ";
		
		/** Hex显示和字符显示区域分割符*/
		static final String PARTITION = ";";
		
		static IByte2String byte2HexUpper;
		
		static IByte2String byte2HexLower;
		
		static IByte2String byte2ASCII;
		
		
	} 
	
	interface IByte2String {
		public String byte2String(byte b); 
	}
	
	class Byte2HexUpper implements IByte2String {
		public String byte2String(byte b) {
			int high = 0x0F & b>>4;
			int low  = 0x0F & b;
			return new String(new char[] {Configuration.HEX_UPPER_CASE[high],
								Configuration.HEX_UPPER_CASE[low]});
		}
	}
	
	class Byte2HexLower implements IByte2String {
		public String byte2String(byte b) {
			int high = 0x0F & b>>4;
			int low  = 0x0F & b;
			return new String(new char[] {Configuration.HEX_LOWER_CASE[high],
							Configuration.HEX_LOWER_CASE[low]});
		}
	}
	
	class Byte2ASCII implements IByte2String {
		private final String INVISIBLE_SUBSTITUTION = ".";
		
		public String byte2String(byte b) {
			return (Character.isWhitespace(b) || Character.isLetterOrDigit(b)) ? new String(new byte[]{b}) : INVISIBLE_SUBSTITUTION;
		}
	}
}
 

 

分享到:
评论

相关推荐

    hex2byte byte2hex

    ### hex2byte与byte2hex知识点详解 在计算机科学领域,数据经常需要在不同的格式之间进行转换,以适应各种应用场景的需求。例如,在网络通信、文件存储等场景中,经常需要将二进制数据(通常表示为`byte`数组)转换...

    010.Editor.x64.v6.0.1.Cracked

    Hex editors are used to edit the individual bytes of binary files,and advanced hex editors such as 010 Editor can also edit hard drives, floppy drives, memory keys, flash drives, CD-ROMs, processes, ...

    010.Editor.x32.v6.0.1.Cracked

    Hex editors are used to edit the individual bytes of binary files,and advanced hex editors such as 010 Editor can also edit hard drives, floppy drives, memory keys, flash drives, CD-ROMs, processes, ...

    Python中String, Bytes, Hex, Base64之间的关系与转换方法详解工程文件

    Program : Type Hint, String, Bytes, Hex, Base64 详解博客地址:https://blog.csdn.net/m0_52316372/article/details/125689591

    String(含Hex)与Byte数组互相转换[代码]

    在Java或类似的编程语言中,我们经常会遇到需要将字符串(String)与字节数组(Byte[])以及十六进制表示的字符串(Hex)进行相互转换的情况。这些转换在处理网络通信、文件存储、加密解密等领域尤为关键。下面我们...

    C#【文件操作篇】hex文件转bin文件

    在C#编程环境中,有时我们需要处理不同格式的二进制数据,例如将十六进制(Hex)文件转换为二进制(Bin)文件。这个过程通常涉及到对文件内容的读取、解析、转换以及写入等步骤。下面将详细探讨如何使用C#进行Hex到...

    C#编写的 Hex转string文件 串口下载数据

    本项目涉及的主题是"C#编写的Hex转string文件串口下载数据",这涵盖了两个主要方面:HEX文件处理和串口通信。下面我们将深入探讨这两个核心知识点。 首先,HEX文件处理是编程中常见的任务,尤其是在低级硬件交互...

    byte数组转化为hex

    public static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { // 将字节转换为16进制的两个字符 int halfByte = (b & 0xF0) &gt;&gt; 4; int byteVal = (b & ...

    HxD HeX Editor 英文绿色版

    16 Bit Intel Hex, 20 Bit Intel Hex, 32 Bit Intel Hex - Checksum-Generator: Checksum-8, ..., Checksum-32, CRC-16, CRC-16 CCITT, CRC-32, Custom CRC, SHA-1, SHA-256, SHA-384, SHA-512, MD-2, MD-4, MD5 ...

    8051-hex 說明

    【部分内容】提到“HEX8051intelHEXHEXExample.hex16HEX***H16Bytes10HHEXBytes161”,这似乎是在描述一个HEX文件的典型结构。HEX文件由多行组成,每行以冒号":"开始,后面跟随该行的字节数、地址、记录类型、数据和...

    浮点数转四字节数HexToByte

    string hexString = BitConverter.ToString(bytes).Replace("-", ""); ``` 在Python中,可以使用struct模块进行转换: ```python import struct floatValue = 3.14 hexString = struct.pack('f', floatValue).hex...

    VB编程资源大全(英文源码 文件)

    &lt;END&gt;&lt;br&gt;59,BINVIEW.zip BINVIEW is a 400 byte scrolling binary viewer that can display any part of any file as decimal bytes, hex bytes, signed, unsigned and long integers or as floating point ...

    CRC32HEX+C#调用程序.zip

    CRC32HEX+C#调用程序是一个关于计算CRC32校验码并将其转换为十六进制(HEX)表示的解决方案。CRC32,全称是Cyclic Redundancy Check with 32 bits,是一种广泛应用于数据传输和存储中的错误检测方法。它通过计算数据...

    hex2bin_2.2_XiaZaiBa.zip

    Specifying this starting address will put pad bytes in the binary file so that the data supposed to be stored at 0100 will start at the same address in the binary file. -v Verbose messages for ...

    脚本 bin 头hex hex to bin

    bin_data = bytes.fromhex(hex_string) # 转换为二进制数据 ``` 对于“bin头hex”,这可能是指查看或处理二进制文件的开头部分(即头部)的十六进制表示。在Python中,可以使用`open()`函数以二进制模式打开文件,...

    16 进制编辑工具 Hex Editor Neo Ultimate Edition 6.52.00 + x64.zip

    剪贴板操作,Bytes, Words, Double Words, Quad Words等双打编辑模式。 十六进制编辑器的使用范围:二进制文件,补丁,DLLs,AVI文件,MP3文件,JPG文件 16 进制编辑工具 Hex Editor Neo Ultimate Edition 中文...

    Hex Editor Neo Ultiamate 6.x Patch

    剪贴板操作,Bytes, Words, Double Words, Quad Words等双打编辑模式。 十六进制编辑器的使用范围:二进制文件,补丁,DLLs,AVI文件,MP3文件,JPG文件。 Free Hex Editor Neo主要特点: 支持使用正则表达式在替换...

    对Python3中bytes和HexStr之间的转换详解

    ### Python3中Bytes与HexStr之间的转换详解 在Python编程中,经常需要处理不同格式的数据。其中,bytes和HexStr是两种常见的数据表示形式。本文将深入探讨如何在Python3中实现bytes与HexStr之间的相互转换,并通过...

    xxd(hexdump),16进制打印

    2. `-g bytes`:设定每组数值的大小,可以是1(字节),2(半字),4(字)或者8(双字)。 3. `-i`:将输出格式化为C语言的`unsigned char`数组,方便直接复制到源代码中。 4. `-s offset`:指定从文件的哪个偏移量...

    Java中byte[]、String、Hex字符串等转换的方法

    Java中byte[]、String、Hex字符串等转换的方法 Java中byte[]、String、Hex字符串等转换的方法是非常重要的知识点,这些转换方法在实际开发中经常被使用。下面将详细介绍这些转换方法。 byte[]和byte的合并 在Java...

Global site tag (gtag.js) - Google Analytics