-1

我正在编写 c++ 代码将 ebcdic 转换为 ascii
我的 main() 如下所示

int main()
{
   char text[100];
   int position;
   int count;

   printf("Enter some text\n");
   cin >> text;

   char substring[] = "\\x";
   if(strlen(text)  2 != 0)
   {
      cout << "Length of the string is not even" << endl;
   }
   else
   {
      position = 1;
      int len_string;
      len_string = strlen(text)/2;
      cout<<"len_string"<<len_string<<endl;

      for (count = 0; count < len_string;count++)
      {
         insert_substring(text, substring, position);
     printf("text is s\n",text);
     position  = position + 4;
      }
   }

   ebcdicToAscii((unsigned char*)text);
   cout << "Converted text" <<text << endl;

   char str[]="\xF5\x40\x40\x40\x40\xD4"; //Hardcoded string
   ebcdicToAscii((unsigned char*)str);
   printf ("converted str is s\n", str);

   return 0;
}

输出:

    Enter some text
    F54040404040D4
    len_string7
    text is \xF54040404040D4
    text is \xF5\x4040404040D4
    text is \xF5\x40\x40404040D4
    text is \xF5\x40\x40\x404040D4
    text is \xF5\x40\x40\x40\x4040D4
    text is \xF5\x40\x40\x40\x40\x40D4
    text is \xF5\x40\x40\x40\x40\x40\xD4
    Converted text**?*?*?*?*?*
    converted str is 5    M

在转换之前,我需要在字符串前面附加 \x

例子:

F540404040D4必须插入转义序列 \x

我已经写了逻辑,所以我得到了输出:

\xF5\x40\x40/x40\x40\xD4

现在开始使用 ebcdic 到 ascii 的转换

ebcdicToAscii((unsigned char*)text);

但我没有得到想要的输出。

同时,当我将字符串硬编码为

\xF5\x40\x40/x40\x40\xD4

输出符合预期

即5M

我很困惑。请指导我。我没有在代码中显示调用函数,假设它给出了正确的返回。

4

1 回答 1

1

你不应该插入\x输入的字符串,顺便说一句,不管有没有插入,这都行不通。

这里:

char str[]="\xF5\x40\x40\x40\x40\xD4";

这只是指示,例如F5应该使用带有此 ascii 代码的十六进制数字和字符(不仅仅是符号 F 和 5)。在这里查看更多信息:\x 在 c/c++ 中是什么意思?

你应该从你的输入构造字符串,它不仅会存储符号,而且每 2 个字节用于 ascii 代码。

例如,您可以使用以下代码进行转换:

#include <iostream>
#include <string>

int main()
{
   const std::string s ="F540404040D4";
   std::string converted;
   converted.reserve(s.size() / 2);
   for (size_t i = 0; i < s.size(); i += 2)
   {
      const std::string tmp = s.substr(i, 2);
      const int a = std::strtol(tmp.c_str(), 0, 16);
      converted += static_cast<char>(a);
   }
   std::cout << converted.size() << std::endl;
}
于 2015-07-30T11:48:26.713 回答