【问题标题】:Error while converting string from EBCDIC to ASCII in C/C++在 C/C++ 中将字符串从 EBCDIC 转换为 ASCII 时出错
【发布时间】:2015-07-30 11:38:23
【问题描述】:

我正在编写 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

输出符合预期

即 5 百万

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

【问题讨论】:

  • 没有C/C++语言!

标签: c++ type-conversion ascii ebcdic


【解决方案1】:

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

这里:

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

这只是一个指示,例如 F5 是十六进制数字,并且应该使用带有这个 ascii 代码的字符(不仅仅是符号 F 和 5)。 在这里查看更多信息:What does \x mean in 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;
}

【讨论】:

  • 我想在字符之间强行附加 '\x' 并且稍后必须将此转换后的字符串传递给 ASCII 值示例:\xf5 -->5
  • 不附加 \x 可以获得所需的输出:5 M ??有可能吗??
  • @NikhilS。添加 '\x' 没有意义,您只需在字符串中添加两个符号。查看转换示例。
  • @ForEveR: OP 混淆了源代码中的文字符号\xXX 与相同序列的用户输入
  • @Jongware 是的,我知道这一点,但正如我所想,我在答案的第一部分解释了这一点。
猜你喜欢
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多