rookie_rockie


hi
i have some queries

1)i have a string(not hexadecimal ) and i want to convert it to a (string )hexadecimal

2) after that i want to store it in a byte[]-- have tried getByte()

for 1) i have tried

string hex = "7B"; // must be hexadecimal for it to work

int myInt = Convert.ToInt32(hex, 16);

Console.WriteLine("{0}",myInt);



for 2) i have tried ascii encoding, utf8 encoding, unicode encoding, however i dont understand the difference.



i have also researched on the convert class and the string.parse class.


can someone pls give me some advice.thanks in advance.




Re: Visual C# General converting values--need help

Steve Py

Just Google the web on 'C# hexadecimal "byte array"' and you'll have more than enough code samples.






Re: Visual C# General converting values--need help

rookie_rockie

been there done that





Re: Visual C# General converting values--need help

boban.s

store int value in byte array:
int a = 5;
byte[] data = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(a), 0, data, 0, 4);

to convert byte array data that contain int number:
int b = BitConverter.ToInt32(data, 0);




Re: Visual C# General converting values--need help

Pace

As far as help for #1 I would suggest...

string not_hex = "255";
int temp = int.Parse(not_hex); //Parses the string to find the # inside.
string hex = (temp).ToString("x"); //The x is a format string that says to convert it to hex.
//Now you have ff stored in hex




Re: Visual C# General converting values--need help

Peter Ritchie

You can't convert a string to hexadecimal. Unless you mean a textual representation of an integer. If you're starting with a textual representation of an integer, just use Int32.TryParse(). Once you have an Int32 value you can simply use int32Value.ToString("X") to convert it to hexadecimal. To convert a string to a byte array, you'll can use the ASCIIEncoding.GetBytes method. For example:

Code Snippet

String text = "1234";

Int32 number;

if(Int32.TryParse(text, out number))

{

text = number.ToString("X");

ASCIIEncoding ascii = new ASCIIEncoding();

byte[] bytes = ascii.GetBytes(text);

}






Re: Visual C# General converting values--need help

rookie_rockie

thank you very much, it works