How to convert a gi-normous integer (in string format) to hex format? (C#)
Oh, that's easy:
var s = "843370923007003347112437570992242323";
var result = new List<byte>();
result.Add( 0 );
foreach ( char c in s )
{
int val = (int)( c - '0' );
for ( int i = 0 ; i < result.Count ; i++ )
{
int digit = result[i] * 10 + val;
result[i] = (byte)( digit & 0x0F );
val = digit >> 4;
}
if ( val != 0 )
result.Add( (byte)val );
}
var hex = "";
foreach ( byte b in result )
hex = "0123456789ABCDEF"[ b ] + hex;
How to convert an integer to fixed length hex string in C#?
Use a number after the X format specifier to specify the left padding : value.ToString("X4")
Numeric Converter (big integers in string format)
Perhaps the code is easier to understand if you compare the algorithm to the simpler version where the integer can be represented in an int
. Then result
would be a 32 bit integer which you would initialize to 0 and for each digit you would multiply the existing value of result
with 10 and add the next digit:
int result = 0;
foreach ( char c in s ) {
int val = (int)( c - '0' );
result = 10*result + val;
}
For big integers you need a byte array to represent the integer and the loop that you want to understand is a way to multiply the value in the byte array of unknown length with 10 while also adding the digit value. Because multiplying by 10 is not a simple bit shift you need that extra code.
Convert a big Hex number (string format) to a decimal number (string format) without BigInteger Class
Here's a quick-and-dirty implementation that can work with arbitrarily-large numbers. The aim of this implementation is simplicity, not performance; thus, it should be optimized drastically if it's to be used in a production scenario.
Edit: Simplified further per Dan Byström's implementation of the inverse decimal-to-hex conversion:
static string HexToDecimal(string hex)
{
List<int> dec = new List<int> { 0 }; // decimal result
foreach (char c in hex)
{
int carry = Convert.ToInt32(c.ToString(), 16);
// initially holds decimal value of current hex digit;
// subsequently holds carry-over for multiplication
for (int i = 0; i < dec.Count; ++i)
{
int val = dec[i] * 16 + carry;
dec[i] = val % 10;
carry = val / 10;
}
while (carry > 0)
{
dec.Add(carry % 10);
carry /= 10;
}
}
var chars = dec.Select(d => (char)('0' + d));
var cArr = chars.Reverse().ToArray();
return new string(cArr);
}
how to convert my decimal thread ID to hex and make it appear in hex format in log4net conversion pattern?
You could write a converter like this:
public sealed class HexPatternConverter : PatternLayoutConverter
{
override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
long id;
if (long.TryParse(loggingEvent.ThreadName, out id))
{
writer.Write(id.ToString("X"));
}
else
{
writer.Write(loggingEvent.ThreadName);
}
}
}
then you configure the layout like this:
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%hex_thread] %message%newline" />
<converter>
<name value="hex_thread" />
<type value="YourNamespace.HexPatternConverter" />
</converter>
</layout>
Obviously you can use this converter in your pattern as you see fit and you will also need to tweak the converter so that it prints the hex value exactly as you want it.
Related Topics
Performance Surprise with "As" and Nullable Types
Difference Between Events and Delegates and Its Respective Applications
How to Move and Resize a Form Without a Border
How to Get the Exif Data from a File Using C#
Requested Registry Access Is Not Allowed
Iterate Two Lists or Arrays with One Foreach Statement in C#
Best Way to Resolve File Path Too Long Exception
Why Does This Floating-Point Calculation Give Different Results on Different MAChines
How to Pass Parameters to Threadstart Method in Thread
Finding the Default Application for Opening a Particular File Type on Windows
Type or Namespace Name Does Not Exist
Why Does Casting Int to Invalid Enum Value Not Throw Exception
How to Securely Save Username/Password (Local)
Convert an Image (Selected by Path) to Base64 String
Best /Fastest Way to Read an Excel Sheet into a Datatable
How to Pass the Smart Screen on Win8 When Install a Signed Application