Daily Knowledge Drop
The Convert
class can be used to convert any integer value to it's corresponding value of a different base
.
Binary
(base 2), Octal
(base 8), Decimal
(base 10) and Hexadecimal
(base 16) are supported.
Convert class
Using the Convert
class to perform the conversion is incredibly simple:
var intValue = 642;
// use the ToString method, specifying the new base
var binary = Convert.ToString(intValue, 2);
var octal = Convert.ToString(intValue, 8);
var hex = Convert.ToString(intValue, 16);
Console.WriteLine(binary);
Console.WriteLine(octal);
Console.WriteLine(hex);
The output is as follows:
1010000010
1202
282
Negative values are also supported:
var intValue = 642;
// use the ToString method, specifying the new base
var binaryNeg = Convert.ToString(intValue * 1, 2);
var octalNeg = Convert.ToString(intValue * -1, 8);
var hexNeg = Convert.ToString(intValue * -1, 16);
Console.WriteLine(binaryNeg);
Console.WriteLine(octalNeg);
Console.WriteLine(hexNeg);
The output is as follows:
11111111111111111111110101111110
37777776576
fffffd7e
And that's all there is to it - simple and occasionally useful!
Notes
In my almost 20 years of programming, I don't think I've ever had to perform these kinds of conversions (outside of assignments at university), so this functionality is probably not useful for every day development for most applications - however when the need does arise, it's useful to know it can be easily implemented.
References
Daily Drop 99: 20-06-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.On This Page