如何将十六进制数转换为c ++中的字符?

时间:2017-04-07 16:31:40

标签: c++ string hex memory-editing

我正在尝试将十六进制数转换为C ++中的字符。 我查了一下,但找不到适合我的答案。

这是我的代码:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <form name="priceForm" novalidate>
      <div class="form-group" ng-class="{'has-error': priceForm.NetMax.$invalid && priceForm.NetMax.$dirty }">
        <label>Max Price:</label>
        <input class="form-control" name="NetMax" type="number" min="0.00" step="0.01" max="9999.99" ng-step="0.01" ng-model="Prices.Net.max" />
      </div>
    </form>

    <p>
      Try reducing the input to 9999.97. For some reason it is invalid.
    </p>
  </div>
</div>

Base [0]将返回十六进制数字,如: 0000005B

如果你到这里http://string-functions.com/hex-string.aspx并输入0000005B作为输入,则输出字符“[”。我怎么也输出[?

2 个答案:

答案 0 :(得分:0)

要将数字打印为字符,您可以将其分配给char变量或将其转换为char类型:

unsigned int value = 0x5B;
char c = static_cast<char>(value);
cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(value) << "'\n";

您也可以使用snprintf

char text_buffer[128];
unsigned int value = 0x5B;
snprintf(&text_buffer[0], sizeof(text_buffer),
         "%c\n", value);
puts(text_buffer);

示例程序:

#include <iostream>
#include <cstdlib>

int main()
{
    unsigned int value = 0x5B;
    char c = static_cast<char>(value);
    std::cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(value) << "'\n";

    std::cout << "\n"
              << "Paused.  Press Enter to continue.\n";
    std::cin.ignore(1000000, '\n');
    return EXIT_SUCCESS;
}

输出

$ ./main.exe
The character of 0x5B is '[` and '['

Paused.  Press Enter to continue.

答案 1 :(得分:-2)

试试这个:

std::cout << "0x%02hX" << Base[0] << std::endl;

输出应为:0x5B,假设Base [0]为0000005B。