String to Byte Array
I've got the below code. What I'm trying to do is get the values entered by the user into textbox4 and place them into a byte array.
But it's not working right. Once I go over the value of 255 into the text box I do not get the correct value displayed in the console when i try adding OUTBuffer + OUTBuffer.
private void button1_Click(object sender, EventArgs e)
Byte OUTBuffer = new byte;
int decValue = Convert.ToInt16(textBox4.Text);
OUTBuffer = 0;
OUTBuffer = 0x80;
byte intBytes = BitConverter.GetBytes(decValue);
Array.Copy(intBytes, 0, OUTBuffer, 2, intBytes.Length);
Console.WriteLine(OUTBuffer + OUTBuffer);
Any help here will be appreciated.
What exactly do you get and what do you think is the correct value?
If this is an ASCII string...Encoding.ASCII.GetBytes(string).
For example I entered 800 into the text box and the result in the console is 35. I should be getting the same integer value returned.
Originally Posted by nvoigt
First an Int32 is 4 bytes long. You are only looking at two of the bytes and saying it should be the same. Now this isn't your issue, but ...
Did you really expect the values to add up to 800? Do you not understand that the first byte is how many '1's are in the number, and that the 2nd byte is how many '256's are in the number? If you actually look at the values stored you'll see that the first is 32 and the second is 3. 3 * 256 = 768, 768 + 32 = 800 so you are getting exactly the right value.
Review number bases and how positional number systems (like our decimal system or this one, which is technically base 256) work.