将六角形字符串转换为十六进制值 [英] Convert Hex String to Hex Value

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

问题描述

我有一个大的十六进制字符串

  abcdef ... 
pre>

,我想将其转换为

  0xab 0xcd 0xef 

有什么功能吗?



也可以告诉我,当人们问这些输入是ASCII还是不是什么意思?
abcdef表示为字符串。不确定是否是ASCII。不知道他们的意思。我对编程非常新,所以在这里的帮助将不胜感激。我有一个巨大的字符串,我需要使用在我的数组,并将其转换为上述格式将帮助我用十六进制字符串初始化我的数组。

解决方案

可以使用字符串流。

  #include< iostream> 
#include< sstream>
#include< vector>

int main(int,char **)
{
const char * str =AFAB2591CFB70E77C7C417D8C389507A5;
const char * p1 = str;
const char * p2 = p1;

std :: vector< unsigned short>输出;

while(* p2!= NULL){
无符号短字节;

++ p2;
if(* p2!= NULL){
++ p2;
}

std :: stringstream sstm(std :: string(p1,p2));

sstm.flags(std :: ios_base :: hex);
sstm>>字节;

output.push_back(byte);

p1 + = 2;
}

for(std :: vector< unsigned short> :: const_iterator it = output.begin(); it!= output.end(); ++ it){
std :: cout<< std :: hex<< std :: showbase<< * it< \t<< std :: dec< std :: noshowbase<< * it< \\\
;
}

std :: cout<< 按任意键继续 ...;
std :: cin.get();
}

请注意,如果使用 unsigned char 而不是 unsigned short 从字符串流的转换试图将其转换为ASCII字符,它不工作。


I have a large hex string

abcdef...

and I want to convert it to

0xab 0xcd 0xef 

Are there any functions that do that?

Also could you tell me what I means when people ask are those inputs in ASCII or not? abcdef are represented as a string. Not sure if that is ASCII or not. not sure what they mean. I am very new to programming so help here would be appreciated. I have a huge string that I need to use in my array and converting it into the aforementioned format will help me initialize my array with the hex string.

解决方案

You can do this using string streams.

#include <iostream>
#include <sstream>
#include <vector>

int main( int , char ** )
{
  const char *str = "AFAB2591CFB70E77C7C417D8C389507A5";
  const char *p1  = str;
  const char *p2  = p1;

  std::vector<unsigned short> output;

  while( *p2 != NULL ) {
    unsigned short byte;

    ++p2;
    if( *p2 != NULL ) {
      ++p2;
    }

    std::stringstream sstm( std::string( p1, p2 ) );

    sstm.flags( std::ios_base::hex );
    sstm >> byte;

    output.push_back( byte );

    p1 += 2;
  }

  for( std::vector<unsigned short>::const_iterator it = output.begin(); it != output.end(); ++it ) {
    std::cout << std::hex << std::showbase << *it << "\t" << std::dec << std::noshowbase << *it << "\n";
  }

  std::cout << "Press any key to continue ...";
  std::cin.get();
}

Note that if you use unsigned char instead of unsigned short the conversion from stringstream attempts to convert it into an ASCII character and it doesn't work.

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

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