2

I am giving the input to console program as "Hai My Name is KrishNA" and that string is converted in to ascii characters and I'm getting output as 543777096. I want If I give the same number as input I want the same output as above in the same program and for space the ascii value is 32 i want to skip that space.I wrote the c# program Below

string s1;
s1 = Console.ReadLine();

byte[] bytes = Encoding.ASCII.GetBytes(s1);
int result = BitConverter.ToInt32(bytes, 0);
//foreach (int r in bytes)
//{
Console.Write(result);

//}
//byte[] array = new byte[result];


byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s1);

foreach (int a in buffer)
{
    Console.WriteLine(buffer);
}

please help me on this

1
  • So you get the first 4 bytes of the characters ("Hai "), drop the rest and convert it into a 32 bit integer. What did you expect? Commented Jun 27, 2016 at 10:56

3 Answers 3

1

Try this one

string s1;
s1 = Console.ReadLine();

byte[] bytes = Encoding.ASCII.GetBytes(s1);
int result = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(result);

String decoded = Encoding.ASCII.GetString(bytes);
Console.WriteLine("Decoded string: '{0}'", decoded);
Sign up to request clarification or add additional context in comments.

Comments

0

You can not convert a string to single 32 bit integer number, in your program, the number 543777096 represents "Hai " (include space), so you can not convert that number back to the first string. Use loop to convert each 4 characters to Int32 number, so your string should be represented by an array of Int32 number.

Comments

0

It is completely unclear what are you use the int result for.

If you want to print the numbers to the console (or into a text file) use a string instead.

byte[] bytes = Encoding.ASCII.GetBytes(s1);
string result = bytes.Aggregate("", (acc, b) => (acc.Length == 0 ? "" : acc + ", ") + b.ToString());
Console.WriteLine(result);

// prints 72, 97, 105, 32, 98, 108, 97, 98, 108, 97 for "Hai blabla"

If you want to leave the spaces out, you can filter the bytes:

result = bytes
         .Where(b => b != 32)
         .Aggregate("", (acc, b) => (acc.Length == 0 ? "" : acc + ", ") + b.ToString());

For longer input texts you should use a StringBuilder instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.