想要添加一个数字到ASCII码的字符或位移位

本文关键字:ASCII 字符 数字 添加 一个 | 更新日期: 2023-09-27 18:07:54

好的,所以我接受字符串输入,将其转换为字符数组,并将其ASCII保存在数组中。

Random r = new Random();
        Console.WriteLine("Enter name : ");
        char[] name = Console.ReadLine().ToCharArray();
        byte[] by = new byte [name.Length];
        int[] arr = new int[name.Length];
        FileStream fs = new FileStream("F:''abc.txt", FileMode.Create, FileAccess.Write);
        for (int i = 0; i < name.Length; i++)
        {
            fs.WriteByte((byte)name[i]);
        }
        for (int i = 0; i <name.Length ; i++)
        {
            by[i] =  ( ((byte )name[i]));
        }
        //for (int i = 0; i < name.Length; i++)
        //{
        //   arr[i] = (byte by[i] (Convert.ToInt16);
        //}
        // fs.WriteByte(48); fs.WriteByte(8); fs.WriteByte(60); fs.WriteByte(80);
        fs.Flush();
        fs.Close();

正在保存ASCII…我们可以把它转换成整型然后在值中加一个特定的数。我基本上是为了加密而做的,这只是其中的一小部分。和此外,如果我们添加的数字是随机生成的……我们可以在解密文本时继续使用它吗?

想要添加一个数字到ASCII码的字符或位移位

正确的方法是:

Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
byte[] ascii = Encoding.ASCII.GetBytes(name);
short[] shorts = bytes.Select(b => (short)b).ToArray();
int[] finalBytes = new int[shorts.length];
int[] randomKey = new int[shorts.length];
int ndx = 0;
Random r = new Random();
foreach (short b in shorts)
{
    int rByte = r.Next(1, 5000);
    int singleByte = b + rByte;
    finalBytes[ndx] = singleByte;
    randomKey[ndx] = rByte;
    ndx++;
}
// finalBytes now holds your data. Do something with it!
// randomKey holds your hash data. To decode this, you'll
// need to subtract the value in randomKey[n] from finalBytes[n]

正如其他人所说,强烈建议不要在任何产品代码中使用此代码!

这可能对您有所帮助。在语言级别上,您实际上不需要转换为数字-您的信息片段更容易作为字符串或字节数组进行操作。

下面的代码替换了现有代码的输出部分,并使用Random实例r对随机数进行按位加法。

byte[] randomNumber = new byte[name.Length];
r.NextBytes(randomNumber);
for (int i = 0; i <name.Length ; i++)
{
    fs.WriteByte((byte)name[i] ^ randomNumber[i]);
}

假设您打算将randomNumber单独存储在某个地方,您将使用与此处用于"加密"相同的方式使用相同的位运算符^进行"解密"。

对于c#,这有点棘手,因为(根据MSDN) Char是16位Unicode数值,而不仅仅是ASCII,所以您必须小心非ASCII符号和解析带有奇怪编码的文件。另一方面,它可以很容易地转换为Unsigned Short Int、Int、Double和其他类型。

基本上,简单的类型转换可以做到这一点:

char character;
int ascii_code = (int)character;
//some fency math and encoding with ascii_code goes here...
char encrypted_char = (char)ascii_code;

不确定,如果Visual Studio允许数学直接使用char类型的变量(C, c++)