Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++로 랜덤 16진수 바이트 생성하기 – rand()와 itoa() 함수 활용 가이드

C++를 사용해 랜덤 16진수(Hexadecimal) 값을 생성하는 프로그램을 만들어 보겠습니다. 이번 글에서는 rand() 함수와 itoa() 함수를 활용하는데, 각 함수가 어떤 역할을 하는지 하나씩 자세히 살펴본 뒤 전체 코드를 구현해 보겠습니다.

rand() 함수란?

rand()는 C++에 미리 정의되어 있는 표준 함수로, <stdlib.h> 헤더 파일에 선언되어 있습니다. 이 함수는 지정한 범위 내에서 난수(random number)를 생성하는 용도로 사용됩니다.

여기서 min_n은 난수 범위의 최솟값, max_n은 최댓값을 의미합니다. 따라서 rand()는 min_n부터 (max_n – 1)까지의 값을 반환합니다. 예를 들어 하한값을 1, 상한값을 100으로 지정하면, rand()는 1부터 (100 – 1), 즉 1부터 99 사이의 값을 반환하게 됩니다.

itoa() 함수란?

itoa()는 10진수 또는 정수 값을 변환하여 반환하는 함수입니다. 지정된 진법(base)을 기준으로 해당 값을 널 종료 문자열(null-terminated string) 형태로 변환하며, 변환된 결과는 사용자가 직접 정의한 배열에 저장됩니다.

문법(Syntax)

itoa(new_n, Hexadec_n, 16);

여기서 new_n은 임의의 정수 값, Hexadec_n은 사용자가 정의한 배열이며, 마지막 인자인 16은 16진수 진법을 나타냅니다. 즉, 이 코드는 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.

알고리즘 단계 요약:

  1. 최댓값(max_n)을 100으로, 최솟값(min_n)을 1로 초기화합니다.
  2. 변환 결과를 저장할 문자형 배열 Hexadec_n과 정수형 변수 new_n, 반복문 카운터 i를 선언합니다.
  3. 5회 반복하면서 rand()로 난수를 생성하고, 그 값을 출력합니다.
  4. itoa()를 호출해 생성된 10진수 난수를 16진수로 변환한 뒤 결과를 출력합니다.

예제 코드

#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

추가 팁

프로그램을 실행할 때마다 서로 다른 난수를 얻고 싶다면, main 함수 시작 부분에 srand(time(NULL))을 추가해 시드(seed)를 설정하는 것이 좋습니다. 시드를 설정하지 않으면 rand()는 매번 동일한 순서의 난수를 반환합니다. 또한 itoa()는 C++ 표준이 아닌 비표준 함수이므로, 이식성이 중요한 프로젝트에서는 std::stringstream과 함께 std::hex 조작자를 사용하는 방식도 좋은 대안이 될 수 있습니다.