Using int as numeric string representation in C #
I'm trying to use an integer as a numeric representation of a string, for example storing "ABCD" as 0x41424344. However, when it comes to output, I need to convert the integer back to 4 ASCII characters. Right now I am using bit shifts and masking as shown below:
int value = 0x41424344;
string s = new string (
new char [] {
(char)(value >> 24),
(char)(value >> 16 & 0xFF),
(char)(value >> 8 & 0xFF),
(char)(value & 0xFF) });
Is there a cleaner way to do this? I tried various roles, but the compiler complained about this as expected.
a source to share
int value = 0x41424344;
string s = Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray());
(The above assumes you are on a little-endian system. For big-endian you can just drop the part .Reverse().ToArray()
, although if you are on a little-endian system it will probably make sense for you to just store "ABCD" as 0x44434241, if possible.)
a source to share
The characters are 16 bits, so you need to encode them into eight bit values in order to pack them into an integer. You can use class Encoding
to convert between characters and bytes and class BitConverter
to convert between bytes and integer
Here's a conversion in both directions:
string original = "ABCD";
int number = BitConverter.ToInt32(Encoding.ASCII.GetBytes(original), 0);
string decoded = Encoding.ASCII.GetString(BitConverter.GetBytes(number));
Note that the byte order of integers depends on the security of the computer. On a small system system, the numeric value "ABCD" would be 0x44434241. To get the reverse order, you can reverse the byte array:
byte[] data = Encoding.ASCII.GetBytes(original);
Array.Reverse(data);
int number = BitConverter.ToInt32(data, 0);
byte[] data2 = BitConverter.GetBytes(number);
Array.Reverse(data2);
string decoded = Encoding.ASCII.GetString(data2);
Or, if you are using framework 3.5:
int number =
BitConverter.ToInt32(Encoding.ASCII.GetBytes(original).Reverse().ToArray() , 0);
string decoded =
Encoding.ASCII.GetString(BitConverter.GetBytes(number).Reverse().ToArray());
a source to share
if the string is never longer than 8 characters and is some sort of Hexstring, you can use the base variable 16 will consider the conversion functions from the Convert class.
string s = "ABCD";
uint i = Convert.ToUInt32( s, 16 );
MessageBox.Show( Convert.ToString( i, 16 ) );
Regards Sorry,
a source to share