Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString("X") produces single digit hex numbers

Tags:

c#

hex

We wrote a crude data scope.

(The freeware terminal programs we found were unable to keep up with Bluetooth speeds)

The results are okay, and we are writing them to a Comma separated file for use with a spreadsheet. It would be better to see the hex values line up in nice columns in the RichTextBox instead of the way it looks now (Screen cap appended).

This is the routine that adds the digits (e.g., numbers from 0 to FF) to the text in the RichTextBox.

  public void Write(byte[] b)          {              if (writting)              {                  for (int i = 0; i < b.Length; i++)                  {                      storage[sPlace++] = b[i];                       pass += b[i].ToString("X") + " ";  //// <<<--- Here is the problem                       if (sPlace % numericUpDown1.Value == 0)                      {                          pass += "\r\n";                      }                  }              }          } 

I would like a way for the instruction pass += b[i].ToString("X") + " "; to produce a leading zero on values from 00h to 0Fh

Or, some other way to turn the value in byte b into two alphabetic characters from 00 to FF

enter image description here

Digits on left, FF 40 0 5 Line up nice and neatly, because they are identical. As soon as we encounter any difference in data, the columns vanish and the data become extremely difficult to read with human observation.

like image 372
User.1 Avatar asked Mar 05 '13 20:03

User.1


People also ask

What is ToString X?

The toString() method returns a string representing the specified Number object.

What is ToString D?

ToString("D") is that it allows you to specify the preceding number of digits. e.g, var i = 123; var stringed = i.ToString("D5");//stringed = 00123.


1 Answers

Use a composite format string:

pass += b[i].ToString("X2") + " "; 

The documentation on MSDN, Standard Numeric Format Strings has examples.

like image 150
Oded Avatar answered Sep 28 '22 03:09

Oded