C++ 中首三位和末三位位元


在這個問題中,我們給定一個數字 N。我們的任務是找到給定整數 N 的前三位和後三位位元的十進位制轉換

讓我們舉一個例子來理解這個問題,

Input : 57
Output : 71

解決方案方法

一個簡單的解決方案是將數字 n 轉換為其二進位制等效值,然後將位元儲存在一個數組中。之後,我們將分別將陣列中的前三位和後三位轉換為數字。這兩組位元的十進位制轉換就是我們的結果。

例如,取數字 80。

80 的二進位制轉換是 1010000。

前三位 (101) 的十進位制轉換是 5。

後三位 (000) 的十進位制等效值為 0。

因此輸出為 5 0。

示例

程式說明我們解決方案的工作原理

#include <bits/stdc++.h>
using namespace std;
void convtbnTodcml(int n)
{
   int arr[64] = { 0 };
   int x = 0, index;
   for (index = 0; n > 0; index++) {
      arr[index] = n % 2;
      n /= 2;
   }
   x = (index < 3) ? 3 : index;
   int d = 0, p = 0;
   for (int index = x - 3; index < x; index++)
      d += arr[index] * pow(2, p++);
   cout << d << " ";
   d = 0;
   p = 0;
   for (int index = 0; index < 3; index++)
      d += arr[index] * pow(2, p++);
   cout << d;
}
int main()
{
   int n = 57;
   cout<<"Decimal conversion of first and last bits of the number "<<n<<" is ";
   convtbnTodcml(n);
   return 0;
}

輸出

Decimal conversion of first and last bits of the number 57 is 7 1

更新於: 2022年2月1日

194 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.