C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ランダムな16進バイトを生成するC++プログラム


乱数を生成できるC++プログラムについて説明します。ここでは、rand()関数とitoa()関数を使用して同じものを実装します。これらの機能について個別に、そして分類的に議論しましょう。

rand(): rand()関数は、C++の事前定義されたメソッドです。 ヘッダーファイルで宣言されています。 rand()は、範囲内の乱数を生成するために使用されます。ここで、min_nは乱数の最小範囲であり、max_nは乱数の最大範囲です。したがって、rand()は、制限値を含めて、min_nから(max_n – 1)までの乱数を返します。ここで、下限と上限をそれぞれ1と100とすると、rand()は1から(100 – 1)までの値を返します。つまり、1から99まで。

itoa(): 10進数または整数の変換された値を返します。値を、指定されたベースを持つnullで終了する文字列に変換します。変換された値をユーザー定義の配列に格納します。

構文

itoa(new_n, Hexadec_n, 16);

ここで、new_nは任意のランダムな整数であり、Hexadec_nはユーザー定義の配列であり、16は16進数の基数です。つまり、inは10進数または整数を16進数に変換します。

アルゴリズム

Begin
   Declare max_n to the integer datatype.
      Initialize max_n = 100.
   Declare min_n to the integer datatype.
      Initialize min_n = 1.
   Declare an array Hexadec_n to the character datatype.
   Declare new_n to the integer datatype.
   Declare i to the integer datatype.
   for (i = 0; i < 5; i++)
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n)
      Print “The random number is:”.
      Print the value of new_n.
      Call itoa(new_n, Hexadec_n, 16) method to
      convert a random decimal number to hexadecimal number.
      Print “Equivalent Hex Byte:”
         Print the value of Hexadec_n.
End.

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main(int argc, char **argv) {
   int max_n = 100;
   int min_n = 1;
   char Hexadec_n[100];
   int new_n;
   int i;
   for (i = 0; i < 5; i++) {
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n);
      //rand() returns random decimal number.
      cout<<"The random number is: "<<new_n;
      itoa(new_n, Hexadec_n, 16); //converts decimal number to Hexadecimal number.
      cout << "\nEquivalent Hex Byte: "
      <<Hexadec_n<<endl<<"\n";
   }
   return 0;
}

出力

The random number is: 42
Equivalent Hex Byte: 2a
The random number is: 68
Equivalent Hex Byte: 44
The random number is: 35
Equivalent Hex Byte: 23
The random number is: 1
Equivalent Hex Byte: 1
The random number is: 70
Equivalent Hex Byte: 46

  1. 16進数から10進数のC++プログラム

    16進数を入力として指定すると、タスクは指定された16進数を10進数に変換することです。 コンピューターの16進数は16を底とし、10進数は10を底とし、0〜9の値で表されますが、16進数は0〜15から始まる数字で、10はA、11はB、12はC、 Dとして13、Eとして14、Fとして15。 16進数を10進数に変換するには、次の手順に従います- 余りから右から左に数字を抽出し、それを0から始まる累乗で乗算し、(桁数)–1まで1ずつ増やします。 16進数から2進数に変換する必要があるため、8進数の基数は16であるため、累乗の基数は16になります。 指定された入力の桁にベースとパワーを掛け

  2. C++での10進数から16進数への変換プログラム

    10進数を入力として指定すると、タスクは指定された10進数を16進数に変換することです。 コンピューターの16進数は16を底とし、10進数は10を底とし、0〜9の値で表されますが、16進数は0〜15から始まる数字で、10はA、11はB、12はC、 Dとして13、Eとして14、Fとして15。 10進数を16進数に変換するには、指定された手順に従います- まず、指定された数値を変換数値の基本値で除算します。例: 6789を16を底とする16進数に変換し、商を取得して格納する必要があるため、6789を16で除算します。余りが0〜9の場合はそのまま保存し、余りが10〜15の場合は、文字形式でA-