将字符串转换为整数,然后再转回字符串。

huangapple go评论67阅读模式
英文:

Convert String to int and again back to String

问题

我有一个类似于 s="DLP_Classification_Rules" 的字符串,需要将其中的某些整数转换一次,然后再使用该整数将字符串转换回原始状态,即 DLP_Classification_Rules。

是否有办法使用 base64 或其他方法来实现类似的操作?

英文:

I have String like s="DLP_Classification_Rules" to convert some integer number and again with that integer I have to convert back same String like DLP_Classification_Rules.

Is there any way to do like this using base64 or something else.?

答案1

得分: 2

不使用Base64,因为结果不是整数,而是字符串。
你要寻找的基本上是将字符串无损压缩为数字的方法(它将比int大得多),这并不容易。

这完全取决于您的用例。您是在单个JVM上运行单个应用程序吗?您正在运行客户端/服务器模块吗?您是否需要在应用程序运行之间保留信息?

例如,您可以使用Map<Integer,String>将所有字符串映射到数字,然后在数字之间传递这些数字,每当您需要字符串本身时,从映射中获取它。不过,如果您需要在本地JVM之外引用这些数字和字符串,除非将映射传输到该JVM,否则帮助可能不大。
您还可以将此映射持久化到文件或数据库中,以在应用程序之间共享信息。
映射中的整数键可以是简单的计数器,比如“map.put(map.size(), s)”(但是然后不要从映射中删除任何内容:)),或者更复杂的方法是使用String的HashCode()函数,它返回一个int:“map.put(s.hashcode(), s)”

英文:

not with Base64, since the outcome is not an integer, but rather a string as well.
what you're looking for is basically a lossless compression of a string to a number (it will be much larger than an int), and that is not easy.

it all depends on your use case. are you running a single application on a single JVM? are you running a client/server module? do you need to keep information between runs of the application?

You can, for example, use a Map<Integer, String> to map all your strings to numbers, and communicate those numbers around, and whenever you need the string itself, pull it from the map. though, if you need to reference these numbers and strings outside of your local JVM then it won't be much help unless you transfer the map over to that JVM.
you can additionally persist this map to a file or database for sharing the information between applications.
your integer key in the map could be a simple counter like "map.put(map.size(), s)" (but then don't remove anything from the map 将字符串转换为整数,然后再转回字符串。 ) or more sophisticated way would be to use the String's HashCode() function which returns an int: "map.put(s.hashcode(), s)"

答案2

得分: 2

尝试这个。

    static BigInteger strToInt(String s) {
        return new BigInteger(s.getBytes(StandardCharsets.UTF_8));
    }

    static String intToStr(BigInteger i) {
        return new String(i.toByteArray(), StandardCharsets.UTF_8);
    }

    String s = "DLP_Classification_Rules";
    BigInteger i = strToInt(s);
    System.out.println(i);
    String r = intToStr(i);
    System.out.println(r);

输出:

1674664573062307484602880374649592966384086501927007577459
DLP_Classification_Rules

或者你可以像这样创建一个字符串池。

public class StringPool {
    private final Map<String, Integer> pool = new HashMap<>();
    private final List<String> list = new ArrayList<>();

    public int stringToInteger(String s) {
        Integer result = pool.get(s);
        if (result == null) {
            result = pool.size();
            pool.put(s, result);
            list.add(s);
        }
        return result;
    }

    public String integerToString(int i) {
        if (i < 0 || i >= pool.size())
            throw new IllegalArgumentException();
        return list.get(i);
    }
}

    StringPool pool = new StringPool();
    String s = "DLP_Classification_Rules";
    int i = pool.stringToInteger(s);
    System.out.println(i);
    String r = pool.integerToString(i);
    System.out.println(r);

输出:

0
DLP_Classification_Rules
英文:

Try this.

static BigInteger strToInt(String s) {
    return new BigInteger(s.getBytes(StandardCharsets.UTF_8));
}

static String intToStr(BigInteger i) {
    return new String(i.toByteArray(), StandardCharsets.UTF_8);
}

and

String s=&quot;DLP_Classification_Rules&quot;;
BigInteger i = strToInt(s);
System.out.println(i);
String r = intToStr(i);
System.out.println(r);

output:

1674664573062307484602880374649592966384086501927007577459
DLP_Classification_Rules

Or you can create a string pool like this.

public class StringPool {
    private final Map&lt;String, Integer&gt; pool = new HashMap&lt;&gt;();
    private final List&lt;String&gt; list = new ArrayList&lt;&gt;();

    public int stringToInteger(String s) {
        Integer result = pool.get(s);
        if (result == null) {
            result = pool.size();
            pool.put(s, result);
            list.add(s);
        }
        return result;
    }

    public String integerToString(int i) {
        if (i &lt; 0 || i &gt;= pool.size())
            throw new IllegalArgumentException();
        return list.get(i);
    }
}

and

StringPool pool = new StringPool();
String s = &quot;DLP_Classification_Rules&quot;;
int i = pool.stringToInteger(s);
System.out.println(i);
String r = pool.integerToString(i);
System.out.println(r);

output:

0
DLP_Classification_Rules

答案3

得分: 2

package com.test;

import java.security.Key;

import javax.crypto.Cipher;

public class EncrypDES {

	private static String strDefaultKey = "des20200903@#$%^&";
	private Cipher encryptCipher = null;
	private Cipher decryptCipher = null;

	/**
	 * @throws Exception
	 */
	public EncrypDES() throws Exception {
		this(strDefaultKey);
	}

	/**
	 * @param strKey
	 * @throws Exception
	 */
	public EncrypDES(String strKey) throws Exception {
		Key key = getKey(strKey.getBytes());
		encryptCipher = Cipher.getInstance("DES");
		encryptCipher.init(Cipher.ENCRYPT_MODE, key);
		decryptCipher = Cipher.getInstance("DES");
		decryptCipher.init(Cipher.DECRYPT_MODE, key);
	}

	/**
	 * @param arrBTmp
	 * @return
	 * @throws Exception
	 */
	private Key getKey(byte[] arrBTmp) throws Exception {
		byte[] arrB = new byte[8];
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
		return key;
	}

	/**
	 * @param strIn
	 * @return
	 * @throws Exception
	 */
	public String encrypt(String strIn) throws Exception {
		byte[] encryptByte = encryptCipher.doFinal(strIn.getBytes());
		int iLen = encryptByte.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = encryptByte[i];
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * @param strIn
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		byte[] decryptByte = decryptCipher.doFinal(arrOut);
		return new String(decryptByte);
	}

	public static void main(String[] args) {
		try {
			String msg1 = "xincan001";
			String key = "20200903#@!";
			EncrypDES des1 = new EncrypDES(key);
			System.out.println("input value:" + msg1);
			System.out.println("After encryption Value:" + des1.encrypt(msg1));
			System.out.println("After decryption Value:" + des1.decrypt(des1.encrypt(msg1)));
			System.out.println("--------------");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

操作结果:

input value:xincan001
After encryption Value:c2cc016fae0bd2008282cae3f2c0be62
After decryption Value:xincan001
--------------
英文:

Hope it can help you

package com.test;
import java.security.Key;
import javax.crypto.Cipher;
public class EncrypDES {
private static String strDefaultKey = &quot;des20200903@#$%^&amp;&quot;;
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
/**
* @throws Exception
*/
public EncrypDES() throws Exception {
this(strDefaultKey);
}
/**
* @param strKey
* @throws Exception
*/
public EncrypDES(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance(&quot;DES&quot;);
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance(&quot;DES&quot;);
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
/**
* @param arrBTmp
* @return
* @throws Exception
*/
private Key getKey(byte[] arrBTmp) throws Exception {
byte[] arrB = new byte[8];
for (int i = 0; i &lt; arrBTmp.length &amp;&amp; i &lt; arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
Key key = new javax.crypto.spec.SecretKeySpec(arrB, &quot;DES&quot;);
return key;
}
/**
* @param strIn
* @return
* @throws Exception
*/
public String encrypt(String strIn) throws Exception {
byte[] encryptByte = encryptCipher.doFinal(strIn.getBytes());
int iLen = encryptByte.length;
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i &lt; iLen; i++) {
int intTmp = encryptByte[i];
while (intTmp &lt; 0) {
intTmp = intTmp + 256;
}
if (intTmp &lt; 16) {
sb.append(&quot;0&quot;);
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
/**
* @param strIn
* @return
* @throws Exception
*/
public String decrypt(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i &lt; iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
byte[] decryptByte = decryptCipher.doFinal(arrOut);
return new String(decryptByte);
}
public static void main(String[] args) {
try {
String msg1 = &quot;xincan001&quot;;
String key = &quot;20200903#@!&quot;;
EncrypDES des1 = new EncrypDES(key);
System.out.println(&quot;input value:&quot; + msg1);
System.out.println(&quot;After encryption Value:&quot; + des1.encrypt(msg1));
System.out.println(&quot;After decryption Value:&quot; + des1.decrypt(des1.encrypt(msg1)));
System.out.println(&quot;--------------&quot;);
} catch (Exception e) {
e.printStackTrace();
}
}
}

operation result

input value:xincan001
After encryption Value:c2cc016fae0bd2008282cae3f2c0be62
After decryption Value:xincan001
--------------

答案4

得分: 1

如果您想要转换的字符串是固定的,您可以为它们创建一个Enum

enum StringInteger {
    DLP_Classification_Rules(1),
    Some_Other_String(2);

    private int value;

    StringInteger(int value) {
        this.value = value;
    }

    public static StringInteger toInt(String value) {
        try {
            return StringInteger.valueOf(value);
        } catch (Exception e) {
            throw new RuntimeException("This string is not associated with an integer");
        }
    }

    public static StringInteger toString(int value) {
        for (StringInteger stringInteger : StringInteger.values()) {
            if (stringInteger.value == value) return stringInteger;
        }
        throw new RuntimeException("This integer is not associated with a string");
    }
}
英文:

If the strings that you want to convert are constant, you can create an Enum for them:

enum StringInteger {
    DLP_Classification_Rules(1),
    Some_Other_String(2);

    private int value;

    StringInteger(int value) {
        this.value = value;
    }

    public static StringInteger toInt(String value) {
        try {
            return StringInteger.valueOf(value);
        } catch (Exception e) {
            throw new RuntimeException(&quot;This string is not associated with an integer&quot;);
        }
    }

    public static StringInteger toString(int value) {
        for (StringInteger stringInteger : StringInteger.values()) {
            if (stringInteger.value == value) return stringInteger;
        }
        throw new RuntimeException(&quot;This integer is not associated with a string&quot;);
    }
}

huangapple
  • 本文由 发表于 2020年9月3日 14:52:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63718300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定