之前做一些JAVA实验中格式的转换总出问题,记录一下常用的转换
package com.ciyako.java;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FormatUtil {
/**
* @Description 十六进制字符串转为二进制,每个十六进制数对应四个二进制数。
* @author Calista
* @date 2023年5月26日上午9:27:00
* @param hex
* @return
*/
public static String Hex2Bin(String hex)
{
String binaryString = "";
String temp;
for(int i = 0;i < hex.length();i++)
{
temp = "0000" + Integer.toBinaryString(Integer.parseInt(hex.substring(i,i+1),16));
binaryString += temp.substring(temp.length()-4);
}
return binaryString.toString();
}
/**
* @Description 二进制转为十六进制,先计算十进制数再转十六进制
* @author Calista
* @date 2023年5月26日上午9:29:38
* @param bin
* @return
*/
public static String Bin2Hex(String bin)
{
String hex = "";
int iTemp;
for(int i = 0;i < bin.length();i += 4)
{
iTemp = 0;
for(int j = 0;j < 4;j++)
{
//用Integer.parseInt(str,2)也可以
iTemp += Integer.parseInt(bin.substring(i+j, i+j+1)) << (4-j-1);
}
hex += Integer.toHexString(iTemp);
}
return hex.toString();
}
/**
* @Description 文本转二进制,先转为字节数组再编为二进制
* @author Calista
* @date 2023年5月26日上午9:30:57
* @param text
* @return
*/
public static String Text2Bin(String text)
{
byte[] bytes = text.getBytes();
String binaryString = "";
String temp;
for (byte b : bytes) {
temp = "00000000" + Integer.toBinaryString(b);
binaryString += temp.substring(temp.length()-8);
}
return binaryString.toString();
}
/**
* @Description 二进制转文本,长度必须是8的倍数
* @author Calista
* @date 2023年5月26日上午9:55:10
* @param bin
* @return
*/
public static String Bin2Text(String bin)
{
byte[] bytes = new byte[bin.length()/8];
for(int i = 0;i < bin.length();i += 8)
{
bytes[i/8] = (byte) Integer.parseInt(bin.substring(i, i+8),2);
}
String text = new String(bytes);
return text;
}
/**
* @Description 文件转二进制,与文本类似
* @author Calista
* @date 2023年5月26日上午9:55:56
* @param filePath 文件路径
* @return
* @throws IOException
*/
public static String File2Bin(String filePath) throws IOException
{
Path path = Paths.get(filePath);
byte[] fileBytes = Files.readAllBytes(path);
String binaryString = "";
String temp;
for (byte b : fileBytes) {
temp = "00000000" + Integer.toBinaryString(b);
binaryString += temp.substring(temp.length()-8);
}
return binaryString.toString();
}
/**
* @Description 二进制转文本
* @author Calista
* @date 2023年5月26日上午9:56:23
* @param bin 二进制字符串
* @param filePath
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static boolean bin2File(String bin,String filePath) throws FileNotFoundException, IOException
{
byte[] bytes = new byte[bin.length()/8];
for(int i = 0;i < bin.length();i += 8)
{
bytes[i/8] = (byte) Integer.parseInt(bin.substring(i, i+8),2);
}
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
outputStream.write(bytes);
}
return true;
}
}