I have a byte array represented by hex values, these are time durations. The data could be converted to integer values and multiplied by a constant to get the timings. The decoding of the data will be saved to a file as a series of hex strings. What would be an efficient way of manipulating hex values?
I was looking at performance issues when dealing with data formats, as I have to work with more than on开发者_StackOverflow中文版e format at different stages (calculations, data display, etc.). Most examples show the conversion from byte[] to hex string ("1A 3C D4"), and viceversa, but I was looking for an alternative, which is to convert to Int16 and use char[] array.
You don't have a byte array representing hex values. You have a byte array representing numbers. The base you represent a number in is only relevant when you're representing it.
To put it a different way: if you thought of your byte array as representing decimal integers instead, how do you imagine it would be different? Is my height different if I represent it in feet and inches instead of metres?
Now, if you're trying to represent 16-bit numbers, I'd suggest that using a byte array is a bad idea. Use a ushort[]
or short[]
instead, as those are 16-bit values. If you're having trouble getting the data into an array like that, please give details... likewise if you have any other problems with the manipulation. Just be aware that until you're writing the data out as text, there's really no such concept as which base it's in, as far as the computer is concerned.
(Note that this is different for floating point values, where the data really would be different between a decimal and a double, for example... there, the base of representation is part of the data format. It's not for integers. Alternatively, you can think of all integers as just being binary until you decide to format them as text...)
From MSDN:
The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". This format is supported only for integral types.
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
byte x = 60;
string hex = String.Format("0x{0:X4}", x);
Console.WriteLine(hex); // prints "0x003C"
精彩评论