有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何获得字符串的双向数字表示?

我需要计算一个双向字符串的数值表示。例如,如果我有一个字符串“US”,我想要一个算法,当应用到“US”时,它会生成一个数字X(int或long)。当另一个算法应用于X时,我想得到“US”。每个字符串由两个字符组成

提前谢谢


共 (4) 个答案

  1. # 1 楼答案

    下面通过使用DataInputStream和DataOutputStream对底层字节数组进行读/写来轻松实现

    public static void main(String[] args) {
    
        String original = "US";
        int i = stringToInt(original);
        String copy = intToString(i);
    
        System.out.println("original: "+original);
        System.out.println("i: "+i);
        System.out.println("copy: "+copy);
    
    }
    
    static int stringToInt(String s) {
    
        byte[] bytes = s.getBytes();
    
        if (bytes.length > 4) {
            throw new IllegalArgumentException("String too large to be" +
                        " stored in an int");
        }
    
        byte[] fourBytes = new byte[4];
        System.arraycopy(bytes, 0, fourBytes, 0, bytes.length);
    
        try {
            return new DataInputStream(new ByteArrayInputStream(fourBytes))
                        .readInt();
        } catch (IOException e) {
            throw new RuntimeException("impossible");
        }
    }
    
    static String intToString(int i) {
    
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            new DataOutputStream(byteArrayOutputStream).writeInt(i);
        } catch (IOException e) {
            throw new RuntimeException("impossible");
        }
    
        return new String(byteArrayOutputStream.toByteArray());
    }
    
  2. # 2 楼答案

    假设字符串的长度为2,即由两个Java char值组成,则可以这样做:

    public int toNumber(String s) {
        return s.charAt(0) + s.charAt(1) << 16;
    }
    public String toString(int number) {
        return (char)number + "" + (char)(number >> 16);
    }
    

    有些Unicode字符(数字超过216)不适合于单个Java char,而是由两个连续的代理表示(由UTF-16表示)。此算法适用于由这两个代理组成的单个字符串,但不适用于由多个此类字符组成的较长字符串

    此外,还有一些int值没有映射回有效的Unicode(或UTF-16)字符串(例如,它们生成未配对的代理项而不是有效字符)。但是每个normal字符串都会转换为int并返回到同一个字符串

  3. # 3 楼答案

    这在一般意义上是不可能的;只有2^64个长值,并且超过2^64个字符串仅由字符X、Y和Q组成

    也许你想要一对哈希表a和B以及一个计数器;如果给你一个字符串,你检查它是否在第一个哈希表中,如果是,返回你存储在那里的值,如果不是,那么你设置

    A[string]=counter; B[counter]=string; counter=1+counter;
    
  4. # 4 楼答案

    您所描述的是双向加密。像this这样的东西可能会帮助你。如果您特别想要一个数值,另一种方法是存储每个字母的字符代码(ASCII代码)。然而,得到的数字将是巨大的(特别是对于非常长的字符串),您可能无法将其存储在32或64位整数中。即使是long在这里也帮不了你

    更新

    根据您的编辑,您只需要两个字符,您可以通过在字符串上使用getBytes()来使用ASCII码。当您需要将其转换回时,前两个数字将对应于第一个字符,而后两个数字将对应于第二个字符