jack jack

jack jack

  • NA
  • 2
  • 2.4k

Introduce NULL Character in HEX File C#

Feb 12 2014 11:11 AM
im using a code which will convert a string(char) to its hex equivalent and write it to a binary file. There is an array declared for the string of size 10. If the string is mentioned as "help" the binary equivalent is displayed as 48 45 4c 50 20 20 20 20 20 20. When there is a space it is displayed as "20"(nothing but its hex equivalent). But if the length of the string is 4 i want the remaining space to be filled with NULL character("00") , so the output will be displayed as "48 45 4c 50 00 00 00 00 00 00". I want the extra space to be filled with null character.

Code what im using:-
 
using System;
using System.IO;
using System.Text;
namespace RandomFileAccess
{
class Test
{

[STAThread]

static void Main(string[] args) {
myName me = new myName("help");
FileStream fs = File.Create("DB.bin");
BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode); //<---------
bw.Write(me.Name.ToCharArray()); //<--------- Writing data as Chararray
bw.Flush();
fs.Close();

}
}

class myName
{
private const int CHAR_ARRAY_LENGTH = 10;

private char[] _name = new char[CHAR_ARRAY_LENGTH];

public myName(string sName)
{
Name = sName;
}

public string Name

{
set
{
string name = value;
int len = name.Length;
if (len < CHAR_ARRAY_LENGTH)
{
_name = name.PadRight(CHAR_ARRAY_LENGTH, ' ').ToCharArray();
}
else if (len > CHAR_ARRAY_LENGTH)
{
_name = name.Substring(0, CHAR_ARRAY_LENGTH).ToCharArray();
}
else
{
_name = name.ToCharArray();
}
}
get
{
return new string(_name);
}
}
}
}

Answers (2)