Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 尝试移动字符串中的每一位_C++_Bit Shift - Fatal编程技术网

C++ 尝试移动字符串中的每一位

C++ 尝试移动字符串中的每一位,c++,bit-shift,C++,Bit Shift,尝试一个编码程序,该程序将把字符串中每个字符的ascii码移位,并打印出新字符,以便以后我可以向左移位并解码消息 范例 “#”=35或100011 100011左移一次=1000110或70 然后我要打印“F” 到目前为止,这就是我的代码。我不理解输出。不确定这是否是因为没有超过127的ascii字符的代码 #include <iostream> #include <string> using namespace std; int main () { int

尝试一个编码程序,该程序将把字符串中每个字符的ascii码移位,并打印出新字符,以便以后我可以向左移位并解码消息

范例

“#”=35或100011

100011左移一次=1000110或70

然后我要打印“F”

到目前为止,这就是我的代码。我不理解输出。不确定这是否是因为没有超过127的ascii字符的代码

#include <iostream>
#include <string>

using namespace std;

int main ()
{
    int i;

    string str ("Hello World");
    string encode, decode;


    for ( i=0; i<str.length(); ++i)
    {
        cout << str[i];
    }

    cout << endl << endl;

    for ( i=0; i<str.length(); ++i)
    {
        cout << (int) str[i] << " ";

    }

    cout << endl << endl;

    for ( i=0; i<str.length(); ++i)
    {
        encode[i] = (str[i] << 1) ;

        cout << encode[i]  << " ";
    }

    cout << endl << endl;

    return 0;
}

不幸的是,OP并没有描述他的操作系统和终端,但我相信他知道发生了什么,并敢于写一个答案

我描述它的第一个字母
H
。(其他所有人也是如此。)


字符(类型
char
)转换为
int
。(Cast是首先执行的,因为它的优先级高于of
操作符,所以让我们列出您要执行的操作:

  • 获取字符串作为输入(即字符数组)
  • 将每个字符转换为整数,然后应用左移位,然后存储在另一个字符串中,即编码,这也是字符数组
  • 那么,现在关于这个问题:

  • 在转换为int之后进行位移位,这很好,但在位移位之后,您尝试将其存储到字符数组中,其中每个字符的最大值为-1字节,并且在转换为整数之后仍然只存储-128到127之间的字符
  • 因此,这就是为什么它永远无法存储超出限制的正确信息

    您仍然可以将其存储为如下所示的整数:

    encode[i] = ((int) str[i]) << 1 ;
    

    encode[i]=((int)str[i])我不知道它为什么是这样写的,因为似乎以\开头的每个值都是以八进制写成的:220八进制=2×8²+2*8+0*1=132+8+0=2*72。我在Visual Studio 2015中尝试过,当
    encode[1]=(str[1]时,它会触发一个断点我期望看到142 202,216,216,222,64,174,222,228,216,200,你的代码<代码> STR[i],代码> <代码> int >代码,同时在第二个<代码>中发送< <代码> >循环。
    
    for ( i=0; i<str.length(); ++i)
    {
        cout << str[i];
    }
    
    for ( i=0; i<str.length(); ++i)
    {
        cout << (int) str[i] << " ";
    
    }
    
    for ( i=0; i<str.length(); ++i)
    {
        encode[i] = (str[i] << 1) ;
    
        cout << encode[i]  << " ";
    }
    
    #include <iostream>
    
    int main()
    {
      std::cout << "\xc3\x9c\n";
      return 0;
    }
    
    encode[i] = ((int) str[i]) << 1 ;