如何将十六进制数字转换为c ++中的字符? [英] How do I convert hex numbers to a character in c++?

查看:138
本文介绍了如何将十六进制数字转换为c ++中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我的代码:

$ p $ char $ mod_tostring(int state, int index,int size){
int stringAddress = lua_tolstring(state,index,0);
const char * const Base =(const char * const)stringAddress;
返回Base [0];
};

Base [0]会返回一个十六进制数字,例如:
0000005B



如果您在这里 http://字符串函数。 com / hex-string.aspx 并将0000005B作为输入输出字符[。如何输出[?

解决方案

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

  unsigned int value = 0x5B; 
char c = static_cast< char>(value);
cout<< 0x5B的字符是'<< c< `和'<< static_cast< char>(value)<< \\\
;

您也可以使用 snprintf



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

示例程序

  #include< iostream> 
#include< cstdlib>

int main()
{
unsigned int value = 0x5B;
char c = static_cast< char>(value);
std :: cout<< 0x5B的字符是'<< c< `和'<< static_cast< char>(value)<< \\\
;

std :: cout<< \\\

<< 暂停,按Enter键继续。
std :: cin.ignore(1000000,'\\\
');
返回EXIT_SUCCESS;
}

输出:

  $ ./main.exe 
0x5B的字符是'[`和'['

暂停。按Enter继续。


I'm trying to convert a hex number to a character in C++. I looked it up but I can't find an answer that works for me.

Here is my code:

char mod_tostring(int state, int index, int size) {
    int stringAddress = lua_tolstring(state, index, 0);
    const char* const Base = (const char* const)stringAddress;
    return Base[0];
};

Base[0] would return a hex number like: 0000005B

If you go here http://string-functions.com/hex-string.aspx and put 0000005B as the input it outputs the character "[". How would I also output [?

解决方案

To print a number as a character, you can either assign it to a char variable or cast it to a char type:

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

You could also use snprintf:

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

Example program:

#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;
}

Output:

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

Paused.  Press Enter to continue.

这篇关于如何将十六进制数字转换为c ++中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆