简体   繁体   中英

How to convert an address in hex string into a byte version of it?

I want to take an address let's say. 0x8402e42d except it is currently in string form which would be just 8402e42d. I want it so I press a button it takes the string out of a textbox which in this case would be 8402e42d, and turn it into 0x8402e42d. I used to know how to do this, but I forgot. Thanks in advance for the help.

I would also prefer to know the easiest way possible of doing this.

To turn it into a string with the hexadecimal prefix, you would just add the prefix:

address = "0x" + address;

To turn the string into a number, you use the Parse method:

uint n = UInt32.Parse(address, NumberStyles.HexNumber);

(Note: You should parse the string without the hexadecimal prefix 0x .)

If you want an array of bytes instead of a single numeric value, use the BitConverter.GetBytes method:

byte[] data = BitConverter.GetBytes(n);

Note that the bytes in the array will be placed in the native order, ie on a little endian system (eg Intel), the least significant byte is first.

You can check the BitConverter.IsLittleEndian property to find out the endianness of the system, and reverse the array to get a specific endianness:

if (BitConverter.IsLittleEndian) {
  Array.Reverse(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM