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

How should I do this?

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

解决方案

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;

or

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

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值