我如何从ASCII转换到十六进制值,也增加char指针

How do I convert from ASCII to hex values and also increment char pointers?

本文关键字:增加 指针 char 十六进制 ASCII 转换      更新时间:2023-10-16
int main()
{
    ifstream infile;
    infile >> std::noskipws;
    size_t size = 0;
    infile.open("tworecords.dat", ios::binary);
    if(infile.is_open())
    {
        infile.seekg(0, ios::end);
        size = infile.tellg();
        infile.seekg(0, ios::beg);
        char *buffer = new char [size];
        infile.read(buffer, size);
        infile.close();
        for(int i=0; i <59; i++)
        {
            c1 = (*buffer);
            buffer++;
            cout << c1 << endl;
        }
        std::cout.write (buffer, size);
        cout << endl;
        delete[] buffer;
    }
    return 0;
}

我正在从文件中读取数据值,它们以ASCII格式出现。我如何使它,以便我可以看到十六进制值的值?

我的第二个问题是我如何增加char指针以增加1,以便它一次读取一个值,就像我在代码中尝试做的那样?

这可能会让您入门。注释代码:

#include <iomanip>
#include <iostream>
int main() {
    // set integer output to uppercase-, hex-mode
    // with '0' as fill character for small byte values
    std::cout << std::hex << std::uppercase << std::setfill('0');
    // declare a buffer
    // note that you could use a std::vector<char> for your reads as well
    std::string input;
    // read a sequence of bytes (TODO: replace with reading from file)
    while(std::getline(std::cin, input)) {
        // iterate over the bytes as unsigned chars (not signed!)
        // to support characters in the negative byte value range (>7F)
        // (using C++11 range-based for loop)
        for (unsigned char i : input)
            // set width format for each value to 2 (00 to FF)
            // (setting is only active for the next insert operation)
            // insert the value as a multibyte integer
            // to get the proper basic_ostream::operator<< overload
            std::cout << std::setw(2) << static_cast<int>(i);
        std::cout << std::endl;
    }
}

使用例子:

$ g++ test.cc -std=c++11
$ echo "Hello World" | ./a.out
48656C6C6F20576F726C64

引用:

  • http://en.cppreference.com/w/cpp/io/manip/hex
  • http://en.cppreference.com/w/cpp/io/manip/uppercase
  • http://en.cppreference.com/w/cpp/io/manip/setfill
  • http://en.cppreference.com/w/cpp/io/manip/setw
  • http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
  • http://en.cppreference.com/w/cpp/language/range-for

至于你关于如何迭代字符数组的其他问题,你有几个选择。请看下面的代码示例:

#include <iostream>
int main() {
    // declare buffer and size
    // intentionally left out null-termination and sizeof()
    // for the purpose of this demonstration
    char buf[] = {'a','b','c','d','e'};
    std::size_t size = 5; 
    // iterate using array indexing
    for (std::size_t i = 0; i < size; i++) std::cout << buf[i];
    std::cout << "n";
    // iterate using pointer
    for (char *p = buf; p != buf+size; p++) std::cout << *p;
    std::cout << "n";
}

注意,您可以(并且应该)使用std::vector<char>作为缓冲区。这有一些好处。最大的缺点:传入和传出函数是微不足道的,你总是可以调用缓冲区的size(),并且,内存管理由标准库完成。

例如(未经测试的代码):

{
    // declare buffer of the appropriate size
    std::vector<char> buffer(size);
    // read data into the buffer
    infile.read(&(buffer[0]), buffer.size());
    infile.close();
    // iterate the buffer using std::vector<char>::iterator
    for (auto it = buffer.begin(); it != buffer.end(), ++it) {
        // do your output operations
    }
} // <-- storage duration of buffer ends automatically where the scope ends

更多的引用:

  • http://en.cppreference.com/w/cpp/container/vector
  • http://en.cppreference.com/w/cpp/container/vector/size
  • http://en.cppreference.com/w/cpp/container/vector/begin
  • http://en.cppreference.com/w/cpp/container/vector/end
  • http://en.cppreference.com/w/cpp/types/size_t
  • http://en.cppreference.com/w/cpp/language/auto
#include <iomanip>
for(int i=0; i <size; i++)  // <-- size, not 59
{
    c1 = buffer[i];         // copy the i'th element of buffer.  If you increment
                            // buffer (as in your example), you can't delete
                            //  it later because you lost the initial address
    cout << hex << c1 << dec << endl;
}

除了十六进制转换,我认为你的循环应该像下面的(见注释):

    for(int i=0; i <size; i++)  // <-- size, not 59
    {
        c1 = buffer[i];         // copy the i'th element of buffer.  If you increment
                                // buffer (as in your example), you can't delete
                                //  it later because you lost the initial address
        cout << c1 << endl;
    }

根据十六进制数字的格式,如果你想逐位输出(例如将'A'转换为10等),一个非常基本的方法是:

    int dec; 
    if (c1>='0' && c1<='9') {
       dec= c1 - '0';   // e..g for '0' (ascii 48) it will make dec= (int)0.
    }
    else 
    if (c1>='A' && c1<='F') {
       dec= 10 + (c1 - 'A');   // e..g for 'A' (ascii 65) it will make dec= (int)10.
    }
    else {
         // should not happen or handle lower chase characters too
    }

另一种使用sscanf的方法是:

// convert one hex digit from c1 into a corresponding decimal number
char hex[2];
int dec;
hex[0]= c1;
hex[1]= '';
sscanf(hex, "%1x", &dec);