一些提示,假设这个练习的目的是教你一些小技巧。
-
string [本质上] 是 char 的序列。
-
char 实际上是一个 16 位无符号整数 (ushort)。
一旦你有了这个整数值,转换为不同基的 [文本表示] 就非常简单了。转换为二进制、八进制或十六进制,因为这些都是 2 的幂次方,只是位移和掩码的问题。转换为十进制(以 10 为底)涉及除法。
以下是一些使用内置转换/格式化实用程序最少的示例。
转换为十六进制(Base 16)。十六进制是表示二进制值的便捷简写。它以 4 组('半字节')为一组,因此每个十六进制“数字”的范围为 16 个值(0-15)。转换是以 4 为单位进行移位和屏蔽的问题。由于我们正在移位和屏蔽,我们可以按顺序构建结果:
private static string CharToHexString( char c )
{
StringBuilder sb = new StringBuilder();
int codePoint = (ushort) c ;
int shiftAmount = 16 ;
do
{
shiftAmount -= 4 ;
// shift the value the correct number of bits to the right and mask off everthing but the low order nibble
int nibble = (codePoint>>shiftAmount)&0x000F ;
sb.Append( "0123456789ABCDEF"[nibble] ) ;
} while ( shiftAmount > 0 ) ;
string value = sb.ToString() ;
return value ;
}
转换为八进制(以 8 为底)本质上与转换为十六进制相同。不同之处在于半字节大小为 3 位,因此数字的域为 0-7(8 个值):
private static string CharToOctalString( char c )
{
StringBuilder sb = new StringBuilder();
int codePoint = (ushort) c ;
int shiftAmount = 18 ; // has to be integral multiple of nibble size
do
{
shiftAmount -= 3 ;
// shift the value the correct number of bits to the right and mask off everthing but the low order nibble
int nibble = (codePoint>>shiftAmount)&0x0007 ;
sb.Append( "01234567"[nibble] ) ;
} while ( shiftAmount > 0 ) ;
string value = sb.ToString() ;
return value ;
}
转换为二进制(以 2 为底),同样,本质上与上述相同,半字节大小为 1 位:
private static string CharToBinaryString( char c )
{
StringBuilder sb = new StringBuilder();
int codePoint = (ushort) c ;
int shiftAmount = 16 ;
do
{
shiftAmount -= 1 ;
// shift the value the correct number of bits to the right and mask off everything but the low order nibble
int nibble = (codePoint>>shiftAmount)&0x0001 ;
sb.Append( "01"[nibble] ) ;
} while ( shiftAmount > 0 ) ;
string value = sb.ToString() ;
return value ;
}
转换为十进制(以 10 为底)。 这有点不同,因为底数不是 2 的幂。这意味着我们必须使用除法来以相反的顺序剥离数字,从低位数字开始。为此,我们将使用Stack<T>,因为堆栈是 LIFO(后进先出)数据结构,这将提供我们需要的反转质量。为此:
private static string CharToDecimalString( char c )
{
Stack<char> digits = new Stack<char>() ;
int codePoint = (ushort) c ;
do
{
int digit = codePoint % 10 ; // modulo 10 arithmetic gives us the low order digit
codePoint = codePoint / 10 ; // integer division by 10 shifts the lower order digit off
digits.Push("0123456789"[digit]);
} while ( codePoint > 0 ) ;
string value = new string( digits.ToArray() ) ; // this pops the entire stack, thus reversing the digits.
return value ;
}