我如何在不丢失信息的情况下保存字符串字节?

问题描述 投票:2回答:1

我正在开发JPEG解码器(我处于Huffman阶段,我想将BinaryString写入文件。例如,假设我们有这个:

String huff = "00010010100010101000100100";

我已经尝试将其转换为以8分割的整数:

huff.split("(?<=\\G.{8})"))

,然后使用FileOutputStream将其写入文件。问题是,在我的示例中,如果我尝试保存“ 00010010”,它将把它转换为18(10010),并且我需要0。

此外,我也尝试将其转换为位集,然后转换为Byte [],但我遇到了同样的问题。

java string int byte bitset
1个回答
-1
投票

您可能想看看UTF-8算法,因为它确实可以满足您的要求。它存储大量数据,同时丢弃零,保留相关数据并对其进行编码以占用更少的磁盘空间。

适用于:Java 7+版本

import java.nio.charset.StandardCharsets;
import java.util.Formatter;

public class UTF8EncodeDecode {

    public static byte[] utf8encode(int codepoint) {
        return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
    }

    public static int utf8decode(byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
    }

    public static void main(String[] args) {
        System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
                "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");

        for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
            byte[] encoded = utf8encode(codepoint);
            Formatter formatter = new Formatter();
            for (byte b : encoded) {
                formatter.format("%02X ", b);
            }
            String encodedHex = formatter.toString();
            int decoded = utf8decode(encoded);
            System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
                    codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
        }
    }
}

https://rosettacode.org/wiki/UTF-8_encode_and_decode#Java

UTF-8是一种可变宽度的字符编码,它能够使用一到四个8位字节来编码Unicode中的所有1,112,064 [nb 1]个有效代码点。[nb 2]该编码由Unicode标准定义,最初是由Ken Thompson和Rob Pike设计。[1] [2]该名称源自Unicode(或通用编码字符集)转换格式– 8位。[3]

它是为了与ASCII向后兼容而设计的。具有较低数值的代码点(通常会更频繁地出现)使用较少的字节进行编码。 Unicode的前128个字符(与ASCII一对一对应)使用与ASCII相同的二进制值的单个字节进行编码,因此有效的ASCII文本也是有效的UTF-8编码的Unicode。由于在将非ASCII代码点编码为UTF-8时不会出现ASCII字节,因此UTF-8可安全地用于大多数以特殊方式解释某些ASCII字符的编程语言和文档语言,例如“ /”(斜杠)。文件名,转义序列中的“ \”(反斜杠)和printf中的“%”。

https://en.wikipedia.org/wiki/UTF-8

© www.soinside.com 2019 - 2024. All rights reserved.