madhusudhan
madhusudhan

Reputation: 400

Convert String to int and again back to String

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.?

Upvotes: 0

Views: 1069

Answers (4)

user4910279
user4910279

Reputation:

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="DLP_Classification_Rules";
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<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);
    }
}

and

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);

output:

0
DLP_Classification_Rules

Upvotes: 2

can
can

Reputation: 21

Hope it can help you

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();
        }

    }
}

operation result

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

Upvotes: 2

Tom Elias
Tom Elias

Reputation: 782

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)"

Upvotes: 2

Titulum
Titulum

Reputation: 11446

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("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");
    }
}

Upvotes: 1

Related Questions