gpt4 book ai didi

java - 字符串base64解码未gziped从little-endian 4字节int到java int

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:19 24 4
gpt4 key购买 nike

我正在尝试在 Android 中实现 TMX 文件,希望有人能提供帮助。基于TMX guide ,为了获得 GID,我必须

first base64 decode the string, then gunzip the resulting data if the compression attribute is set to "gzip" as in the above example. Finally, you can read 4 bytes at a time for each GID from the beginning of the data stream until the end.

我想我已经弄清楚了 Base64 解码和“gunzip”,但下面代码的结果是 27,0,0,0 重复。我认为输出应该是

(0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) (1,2) (2,2) (3,2)

谢谢!

 public static void main( String[] args )
{
String myString = "H4sIAAAAAAAAAO3NoREAMAgEsLedAfafE4+s6l0jolNJiif18tt/Fj8AAMC9ARtYg28AEAAA";

byte[] decode = Base64.decodeBase64(myString);

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
GZIPInputStream gzipInputStream;

int read;
try
{
gzipInputStream = new GZIPInputStream(byteArrayInputStream);

InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 4);

while ( ( read = bufferedReader.read() ) != -1 )
{
System.out.println("read :" + read);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

最佳答案

除字符数据外,请勿使用 Reader 来读取任何内容!

使用DataInput读取整数。用 DataInputStream 装饰您的 GZIPInputStream并使用readInt .

如果整数是小端字节序,则需要反转该类型的字节顺序。 Java 使用网络字节顺序(big-endian)。对于整数,可以使用 Integer.reverseBytes 来完成.

您可以使用以下方式打印十六进制值:

System.out.format("%08x", (int) n);
<小时/>

如何从任意长度的流中读取所有int值:

一种机制是使用 available() 方法来估计剩余字节数:

byte[] ints = {0x00, 0x00, 0x00, (byte) 0xFF,
(byte) 0xAA, (byte) 0xBB, (byte) 0xEE, (byte) 0xFF};
ByteArrayInputStream array = new ByteArrayInputStream(ints);
DataInputStream data = new DataInputStream(array);
while(data.available() > 0) {
int reversed = Integer.reverseBytes(data.readInt());
System.out.format("%08x%n", reversed);
}

一般情况下,available() 不是一个可靠的机制。但是您可以使用缓冲区来增强流以检查数据可用性:

  public static void main(String[] args) throws IOException {
byte[] ints = {0x00, 0x00, 0x00, (byte) 0xFF,
(byte) 0xAA, (byte) 0xBB, (byte) 0xEE, (byte) 0xFF};
ByteArrayInputStream array = new ByteArrayInputStream(ints);
BufferedInputStream buffer = new BufferedInputStream(array);
DataInputStream data = new DataInputStream(buffer);
while(hasData(data)) {
int reversed = Integer.reverseBytes(data.readInt());
System.out.format("%08x%n", reversed);
}
}

public static boolean hasData(InputStream in) throws IOException {
in.mark(1);
try {
return in.read() != -1;
} finally {
in.reset();
}
}

关于java - 字符串base64解码未gziped从little-endian 4字节int到java int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3262348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com