Swift 程式將十進位制轉換為二進位制


本教程將討論如何編寫 Swift 程式將十進位制數轉換為二進位制數。

十進位制數是指基值為 10 的數字。十進位制數也稱為基數為 10 的數字系統,包含 10 個數字:0、1、2、3、4、5、6、7、8、9。在這裡,十進位制數中每個數字的位置權重都是 10 的冪。例如,(89)10 = 8 x 101 + 9 x 100

二進位制數是指基值為 2 的數字。二進位制數也稱為基數為 2 的數字系統,僅包含兩個數字 1 和 0。在這裡,二進位制數中每個數字的位置權重都是 2 的冪。

例如,(1011)2 是一個二進位制數。二進位制數是計算機裝置中最常用的數字系統,其中每個數字都由一個位元表示。

現在,我們使用以下任何一種方法將十進位制(基數為 10)轉換為二進位制(基數為 2)數。

以下是相同的演示 -

輸入

假設我們給定的輸入是 -

Decimal number = 20

輸出

所需的輸出將是 -

Binary number = 10100

方法 1 - 使用按位運算子

我們可以使用按位右移運算子和 AND(&) 運算子將十進位制數轉換為二進位制數。它比算術運算子快得多。

示例

以下程式顯示瞭如何將十進位制數轉換為二進位制數。

import Foundation 
import Glibc

// Decimal Number 
var decimalValue = 59

// String binary number 
var binaryValue = ""

print("Decimal Number: ", decimalValue)

// Converting decimal to binary number 
while(decimalValue > 0) {
   // Perform bitwise AND operation to find 1 and 0 
   if ((decimalValue & 1) == 1){
      // Store “1” 
      binaryValue += "1" 
   } 
   else {
      // Store “1” 
      binaryValue += "0" 
   }
   
   // Right shift the decimal number by 1 
   decimalValue >>= 1 
}

// Reversing the string 
var res = String(binaryValue.reversed())

print("Binary Number: ", res)

輸出

Decimal Number: 59 
Binary Number: 111011

方法 2 - 使用冪

我們還可以透過從數字中提取每個數字,然後將提取的數字乘以基數(10 的冪)並新增到二進位制變數中來將二進位制轉換為十進位制數。在程式結束時,您將在二進位制變數中獲得所有二進位制數字。

示例

以下程式顯示瞭如何將十進位制數轉換為二進位制數。

import Foundation 
import Glibc

// Decimal Number 
var decimalValue = 19

// String binary number 
var binaryValue = 0 
var count = 0.0

print("Decimal Value:", decimalValue)

// Converting decimal to binary number 
while(decimalValue != 0){

   // Extraction rightmost digit from the decimal number using remainder 
   let remainder = decimalValue % 2
   
   // Find power of 10 
   let value = pow(10.0, count)
   
   // Now multiply the digit with the base(power of 2) and add the value to the binaryValue 
   binaryValue += remainder * Int(value)
   
   // Divide the decimal number by 2 
   decimalValue /= 2
   
   // Store the exponent value 
   count += 1 
}

print("Binary Value:", binaryValue)

輸出

Decimal Value: 19 
Binary Value: 10011

方法 3 - 使用預定義函式

我們還可以使用 String(_:radix:) 將十進位制數轉換為二進位制數系統。此方法根據給定的字串/數字和基數建立一個新值。

語法

以下是語法 -

String(value, radix: base)

這裡,value 是數字的 ASCII 表示形式。而 radix 用於將文字轉換為整數值。radix 的預設值為 10,其範圍可以是 2…36。

示例

以下程式顯示瞭如何將十進位制數轉換為二進位制數。

import Foundation 
import Glibc

// Decimal number 
var number = 5

print("Decimal Number:", number)

// Converting decimal to binary 
let BinaryNumber = String(number, radix: 2)

print("Binary Number:", BinaryNumber)

輸出

Decimal Number: 5 
Binary Number: 101

這裡,我們使用以下程式碼將十進位制數 5 轉換為二進位制數 -

let BinaryNumber = String(number, radix: 2)

其中 String(number, radix: 2) 將給定的十進位制數轉換為二進位制數。因此,結果二進位制數為 101。

更新於: 2022-11-30

1K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.