Java 如何将从txt文件读取的字符0s和1s转换为字节?
我想读取一个包含0和1的txt文件,并将它们转换为字节,但首先转换为二进制。e、 g文本文件包含“00101001”。每个字符是1个字节,从文件中读取后得到8个字节。现在我想把它们附加到一个字符串并转换成字节。我应该从8字节中得到1字节,对吗 有更好的选择吗?。 到目前为止我所做的:Java 如何将从txt文件读取的字符0s和1s转换为字节?,java,text-files,Java,Text Files,我想读取一个包含0和1的txt文件,并将它们转换为字节,但首先转换为二进制。e、 g文本文件包含“00101001”。每个字符是1个字节,从文件中读取后得到8个字节。现在我想把它们附加到一个字符串并转换成字节。我应该从8字节中得到1字节,对吗 有更好的选择吗?。 到目前为止我所做的: public byte[] convertBytes(String File1, int length) throws IOException { byte BytesfromFile[]=readInp
public byte[] convertBytes(String File1, int length) throws IOException
{
byte BytesfromFile[]=readInput(File1,length); // readinput() returns (length*8) bytes,contains 48 or 49s.
StringBuilder stringBuilder = new StringBuilder(); //Stringbuilder append chars to build String
byte convertedBytes[]=new byte[BytesfromFile.length/8]; //size of byte array init
int stringToInt;
byte intToByte;
for(int index=0,bitcounter=0,indexCoverted=0;index<BytesfromFile.length;index++,++bitcounter)
{
stringBuilder.append((char) BytesfromFile[index]); //append 48 or 49 casted to char
if(bitcounter==8)
{ String Binary = stringBuilder.toString(); // if 8 bits appended, toString
stringToInt = Integer.parseInt(Binary, 2); // convert Binary String to Int
intToByte = (byte)stringToInt; // cast Int to byte
convertedBytes[indexCoverted++]=intToByte;
bitcounter=0;
stringBuilder.setLength(0); //set length to 0, to append next 8 bit.
}
}
return convertedBytes;
}
public byte[]convertBytes(字符串文件1,int-length)引发IOException
{
byte BytesfromFile[]=readInput(File1,length);//readInput()返回(length*8)字节,包含48或49个字节。
StringBuilder StringBuilder=新建StringBuilder();//StringBuilder将字符附加到生成字符串
byte convertedBytes[]=新字节[BytesfromFile.length/8];//字节数组init的大小
int stringToInt;
字节intToByte;
对于(int index=0,bitcounter=0,indexCoverted=0;index您可以使用基数为2的Byte.parseByte
方法:
byte b = Byte.parseByte(str, 2);
您也可以使用biginger(String val,int-radix)
构造函数快速转换二进制数字的长String
:
String input = "1010010010010101010010010101001";
byte[] arr = new BigInteger(input, 2).toByteArray();
// Result:
// [82, 74, -92, -87]
你的意思是我可以直接将字符串转换为字节,而不是先将其转换为int?是的:不需要显式转换为int
。例如,byte.parseByte(“1010”,2)
返回10。你说我应该从64个字节中得到1个字节是什么意思?我从文本文件中读取了8个字符。“10101001”。每个字符实际上是1字节,例如,第一个字符是1字节,它是49。49二进制是00110001。但我不想转换49,我希望字符0是字节中的单个位。所以你应该从64字节的文件中得到8字节,而不是1字节。不是吗?文件中的1字节给我1位,是的,你是对的。我的错误。我的意思是64位:D。或者更好r 8字节中的1字节。