-1

I'm just starting with the c# programming and as the heading describes, I'm looking for a way to convert a number passed to me as an ASCII character in a byte[] to an integer. I often find the way to convert a hex-byte to ASCII-char or string. I also find the other direction, get the hex-byte from a char. Maybe I should still say that I have the values displayed in a texbox for control.

as an example:
hex- code: 30 36 38 31

Ascii string: (0) 6 8 1

Integer (dez) should be: 681

so far I have tried all sorts of things. I also couldn't find it on the Microsoft Visual Studio website. Actually this should be relatively simple. I am sorry for my missing basics in c#.

3 Answers3

0

Putting together this hex-to-string answer and this integer parsing answer, we get the following:

// hex -> byte array -> string
var hexBytes = "30 36 38 31";
var bytes = hexBytes.Split(' ')
    .Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
    .ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);

// parse string as integer
int x = 0;
if (Int32.TryParse(asciiStr, out x))
{
    Console.WriteLine(x); // write to console
}
else
{
    Console.WriteLine("{0} is not a valid integer.", asciiStr); // invalid number, write error to console
}

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • thanks for your fast Help. I tryed it but i think there was a missunderstanding with byte[]. In fact, hexByte would have to be implemented in this way: byte[] hexBytes = [0x30, 0x36, 0x38, 0x31]; I get this byte[] from TCPIP with StreamReader.ReadBytes(). even if I change the answer from type byte[] to var, I can't do any .Split operation. As far as I know, in these case i don't have to. I also tryed to run through each byte individually, but System.Text.Encoding.ASCII.GetString(...) don`t accept a single byte. – Maximilian Fröhlich May 27 '21 at 09:46
  • @MaximilianFröhlich `var` won't make a difference because it will become `string` once compiled. [See here as an example](https://sharplab.io/#v2:D4AQTAjAsAUCDMACciDCiDetE+UkALIgLIAUAlJtrjSBAAyICGiAvIgEQAWApgDZ8A9hwDc1GjgBuTAE6IARm068BgsKPES6jAMZLu/IfA0wJuOgE5SAZQAuMgJYA7AOYA6VIKc6mt0h2k+AFceAGcALg4AGiYo+XJyMVNcAF9NWBSgA). `var` is syntactic sugar and the compiler works out what type it actually is at compile time. – ProgrammingLlama May 27 '21 at 10:59
  • _"`System.Text.Encoding.ASCII.GetString(...)` don't accept a single byte."_ - Why are you trying to do it one byte at a time? Take my answer from `var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);` downwards, replacing `bytes` with `hexBytes`: [example](https://rextester.com/LIIHY46083). Ultimately the cause for misunderstanding here is that you used the term "hex bytes", suggesting it was a `string`. A byte array is a byte array, regardless whether you initialize it with hex, octal, decimal. There is nothing special stored if you initialize it with hex. – ProgrammingLlama May 27 '21 at 11:01
  • Ok, I got it. My problem was how I read the data from TCPIP or how the data is split. The data now comes in as a byte array and can be used with var asciiStr = System.Text.Encoding.ASCII.GetString(hexBytes); converted to a string. However, I still had to define a substring to remove a ":" before the values. Thank you very much – Maximilian Fröhlich May 27 '21 at 12:40
0

A typical solution of the problem is a Linq query. We should

  1. Split initial string into items
  2. Convert each item to int, treating item being hexadecimal. We should subtract '0' since we have not digit itself but its ascii code.
  3. Aggregate items into the final integer

Code:

using System.Linq;

... 

string source = "30 36 38 31";

int result = source
  .Split(' ')
  .Select(item => Convert.ToInt32(item, 16) - '0')
  .Aggregate((sum, item) => sum * 10 + item);

If you want to obtain ascii string you can

  1. Split the string
  2. Convert each item into char
  3. Join the chars back to string:

Code:

string source = "30 36 38 31";

string asciiString = string.Join(" ", source
  .Split(' ')
  .Select(item => (char)Convert.ToInt32(item, 16)));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

To convert a byte array containing ASCII codes to an integer:

byte[] data   = {0x30, 0x36, 0x38, 0x31};
string str    = Encoding.ASCII.GetString(data);
int    number = int.Parse(str);

Console.WriteLine(number); // Prints 681

To convert an integer to a 4-byte array containing ASCII codes (only works if the number is <= 9999 of course):

int number = 681;
byte[] data = Encoding.ASCII.GetBytes(number.ToString("D4"));
// data[] now contains 30h, 36h, 38h, 31h

Console.WriteLine(string.Join(", ", data.Select(b => b.ToString("x"))));
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276