[英]I am unable to understand the output to my c++ code
I was doing a problem the part of the problem is to shift the a given string of 0 and 1 of a given number n to a given amount (here sft variable taken).我正在做一个问题,问题的一部分是将给定数字 n 的给定字符串 0 和 1 移动到给定数量(这里采用 sft 变量)。 T queries.
T 查询。 I was getting error in right shift while left shift had no problem.
我在右移时出错,而左移没有问题。 The whole code is below -
整个代码如下 -
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
const int m=16;
int n,t;
cin>>t;
int sft;
char ch;
int arr[m];
while(t--)
{
cin>>n;
cin>>sft;
cin>>ch;
bitset<m>bt(n);
cout<<bt<<endl;
if(ch=='R')
{
for(int i=0;i<m;i++)
{
arr[i]=bt[((i+sft)%m)]; // problem is here
// cout<<((i+sft)%m)<<"-"<<bt[((i+sft)%m)]<<" "; // to check what is happening
}
}}}
PROBLEM - The problem is that for a given position in bt string, I am not getting what I am supposed to get it is giving wrong bit I do not know why?问题 - 问题是对于 bt 字符串中给定的 position,我没有得到我应该得到的东西,它给出了错误的位,我不知道为什么?
input:输入:
1(queries) 1(查询)
16(number) 3 (sft) R(right) 16(数字) 3 (sft) R(右)
Output Output
bt string = 0000000000010000 bt 字符串 = 0000000000010000
Position-Bit in bt = 3-0 4-1 5-0 6-0 7-0 8-0 9-0 10-0 11-0 12-0 13-0 14-0 15-0 0-0 1-0 2-0 bt 中的位置位 = 3-0 4-1 5-0 6-0 7-0 8-0 9-0 10-0 11-0 12-0 13-0 14-0 15-0 0-0 1- 0 2-0
The least significant bit is 0, so that should be on the right side, so your output should be:最低有效位是 0,所以它应该在右侧,所以你的 output 应该是:
2-0 1-0 0-0 15-0... 5-0 4-1 3-0
2-0 1-0 0-0 15-0... 5-0 4-1 3-0
or 0000000000000010 (2) which is the right shift for 3 positions of 0000000000010000 (16)或 0000000000000010 (2) 这是 0000000000010000 (16) 的 3 个位置的右移
So your processing is okay for circular right shifting (rolling), but your output is confusing.因此,您的处理对于循环右移(滚动)是可以的,但是您的 output 令人困惑。
For non-circular (logical) shifting, introduce 0 for invalid positions.对于非循环(逻辑)移位,为无效位置引入 0。
See also: https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts另请参阅: https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.