如何在Java中为char添加整数? [英] How do I add an integer to a char in Java?

查看:188
本文介绍了如何在Java中为char添加整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java创建一个密码,但我不能做以下事情:
我想编辑一个char数组的值来加密它

I'm making a Cipher in Java but I can't do the follwing thing: I want to edit the value of a char array to encrypt it

我应该怎么做?

更改每个字符的ASCII值可能就是答案,我不知道;这就是我问你的原因!

Changing the ASCII value of each char might be the answer, I don't know; that's why I'm asking you Guys!

推荐答案

你可以添加 int char ,但结果是 int - 你必须转回 char 将它放回数组中,除非你使用复合赋值运算符:

You can add an int to a char, but the result is an int - you'd have to cast back to char to put it back in the array, unless you use the compound assignment operator:

array[x] += someInt;

array[x] = (char) (array[x] + someInt);

但是,通常此不是执行加密的适当方式。您通常会得到不可打印的字符,或者甚至在Unicode中没有特定含义的字符。相反,大多数加密算法都设计用于处理任意二进制数据 - 即字节数组。

However, usually this isn't an appropriate way of performing encryption. You'll often end up with unprintable characters, or characters which don't even have a specific meaning in Unicode. Instead, most encryption algorithms are designed to work on arbitrary binary data - i.e. byte arrays.

通常你会将字符串转换为字节数组首先(例如,使用 String.getBytes(charset) - 明确指定编码)。然后对字节数组执行加密,为您提供一个新的字节数组。如果确实需要将其转换回文本,请使用base64执行此操作 - 执行使用 new String(encryptedBytes),因为你不再有以正常文本编码编码的文本数据。

Usually you would convert the string into a byte array first (e.g. with String.getBytes(charset) - definitely specify an encoding). Then perform encryption on the byte array, giving you a new byte array. If you really need to convert it back to text, use base64 to do so - do not use new String(encryptedBytes), as you no longer have text data encoded in a normal text encoding.

这篇关于如何在Java中为char添加整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆