一、测试环境
名称 | 版本 |
---|---|
操作系统 | Red Hat Enterprise Linux Server release 7.9 (Maipo) |
CPU | 12th Gen Intel® Core™ i7-12700H |
内存 | 5G |
JDK | 1.8.0_171 |
Scala | 3.1.2 |
二、功能实现
Int类型数据由十进制转换为二进制。
三、源码
object Decimal2Binary {
def PrintDecimalSystemArray(TempArray: Array[Int], TempArraySize : Int): Unit = {
var i: Int = 0
val SpaceNum = 4
for(i <- 0 until TempArraySize){
printf("%d",TempArray(i))
if((i+1) % SpaceNum == 0) {
printf(" ")
}
}
printf("\n")
}
def DecimalSystem2Binary(DecimalNum: Int): Unit = {
val ArraySize: Int = 32
var TempNum: Int = DecimalNum
var RemainderArray: Array[Int] = new Array[Int](ArraySize)
val SystemNum = 2
var i: Int = 0
var Flag: Int = 1 // 1 : + , -1 : -
for(i <- 0 until ArraySize){
if(i == 0 && DecimalNum < 0){
RemainderArray(i) = 1
Flag = -1
}
else {
RemainderArray(i) = 0
}
}
//PrintDecimalSystemArray(RemainderArray, ArraySize)
i = ArraySize - 1
while(TempNum != 0){
RemainderArray(i) = (TempNum % SystemNum).abs
printf("%4d / %d = ",TempNum,SystemNum)
TempNum = TempNum / SystemNum
printf("%4d --- %2d\n",TempNum,RemainderArray(i) * Flag)
i -= 1
}
PrintDecimalSystemArray(RemainderArray, ArraySize)
}
def main(args: Array[String]): Unit = {
DecimalSystem2Binary(-126)
DecimalSystem2Binary(130)
}
}
四、编译
[root@node0 src]# scalac Decimal2Binary.scala -d ../test/
五、测试结果
[root@node0 test]# scala Decimal2Binary
-126 / 2 = -63 --- 0
-63 / 2 = -31 --- -1
-31 / 2 = -15 --- -1
-15 / 2 = -7 --- -1
-7 / 2 = -3 --- -1
-3 / 2 = -1 --- -1
-1 / 2 = 0 --- -1
1000 0000 0000 0000 0000 0000 0111 1110
130 / 2 = 65 --- 0
65 / 2 = 32 --- 1
32 / 2 = 16 --- 0
16 / 2 = 8 --- 0
8 / 2 = 4 --- 0
4 / 2 = 2 --- 0
2 / 2 = 1 --- 0
1 / 2 = 0 --- 1
0000 0000 0000 0000 0000 0000 1000 0010