-3

I am trying to write a method to scramble a message by adding 2 to the byte value of each character and then print the new message. This is what I got so far:

public static void MsgToCode(string value)
    {

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(value);
        foreach (var item in bytes)
        {
            byte b2= item;
            b2 = (byte)(b2 + 2);


        }
        Console.ReadLine();
    }

I tried using b2.ToString inside the foreach statement. But it doesn't work. What am I doing wrong?

  • See here: http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string – sr28 Dec 15 '15 at 10:42
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Albireo Dec 15 '15 at 10:49
  • Are you expecting to convert this back at any point? Or just to scramble it into nonsense? – Matt Hogan-Jones Dec 15 '15 at 10:50
  • `var scrambled = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(value).S‌​elect(b => (byte)(b + 2)).ToArray()); var unscrambled = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(scrambled).S‌​elect(b => (byte)(b - 2)).ToArray());` – Corak Dec 15 '15 at 11:04
  • I intend to convert it back later. I hope to be able to solve that on my own, but we will see how it goes. – Patrik Gustafsson Dec 15 '15 at 13:35

2 Answers2

0

What is going to happen if you try to cast the character(255) + 2 to byte? You might have to reconsider what you are doing here. If you just want to encrypt the text there are several libraries for you to use!

-1

Is this what you are looking for?

public static void MsgToCode(string value)
{

    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(value);
    var sb = new StringBuilder();
    foreach (var item in bytes)
    {
        sb.Append((Convert.ToInt32(item) + 2));
    }
    Console.WriteLine(sb.ToString());
    Console.ReadLine();
}

Or Maybe you want this

static void Main(string[] args)
{
    MsgToCode("Test");
}

public static void MsgToCode(string value)
{
    var bytes = System.Text.Encoding.UTF8.GetBytes(value);
    var newBytes = new byte[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
    {
        var newValue = Convert.ToInt32(bytes[i]) + 2;
        if (newValue > 255)
            newValue -= 255;
        newBytes[i] = Convert.ToByte(newValue);
    }
    Console.WriteLine(System.Text.Encoding.UTF8.GetString(newBytes));
    Console.ReadLine();
}
Theunis
  • 238
  • 1
  • 15