Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I want to convert a data type in a byte address.


+ And i have to escape that "0x" from my data.
And the data type will be as string(i think) but it may be int or whatever.
I don't know what to write in code.
Thanks!
For example:

What I have tried:

public void blabla(string 0xmyaddress)
{
/////// My address will be like : 0x01020304
/////// And i want to convert that address to:
byte [0]= 04;
byte [1]= 03;
byte [2]= 02;
byte [3]= 01; // all in reverse order of bytes, how i did.

//AND there will be my code(i hope)

}
Posted
Updated 27-Sep-18 20:36pm

1 solution

That's possibly more complicated that you think: a string is an array of characters (or it can be thought of, and treated as such) but a char in .NET is not equivalent to a byte, it is a Unicode value and is thus a 16 bit value, unlike byte which is an 8 bit value.

There are ways to convert it, but they depend on "knowing" what the original value in the string were intended to be. If you know that a string contains ASCII data for example - because it's been received from a device that works in ASCII - then it's simple:
C#
string s = ...
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);

But if you don't know the source, then you probably don;t know the content and the conversion is prone to errors.

The next problem is that your example doesn't make a lot of sense: it seend to imply one of three things:
1) You want to convert the name of a local variable to an array of bytes which is silly, and unlikely to be reliable: the name is not necessarily preserved by compilation and may be a random set of letters instead of a literal "Ox01020304"
2) You are trying to convert the "address" of the string to an array of bytes. That's more complicated as well, because the string doesn't have an address directly: it's a reference to an invariant item in heap memory, and the GC is at liberty to move the actual object around in memory if it needs to transparently behind the scenes. To use the address itself, you have to "fix" it's position first, and that isn't something normally needed.
3) If the content of Oxmyaddress is a string "0x01020304" then it's pretty trivial: use Convert.ToInt32 to convert it to an integer, and then BitConverter to get the bytes:
C#
string s = "0x01020304";
int i = Convert.ToInt32(s, 16);
byte[] buffer = BitConverter.GetBytes(i);


But I think you need to consider exactly what you are doing a bit more carefully first...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900