Want to shift bits with addition of 1

Discussion in 'C++' started by LinuxGuy, Jan 16, 2006.

1. LinuxGuyGuest

Hi,

I want to add bits to present number. Shift operator pushes bits and

I want to shift bits and want to add 1 at end

Ex,

1)
suppose Input 0000
for 1 bit I want output as 0001

2)
Input 0100
for 1 bit output should be
1001

any help is welcome.

Thanks

LinuxGuy, Jan 16, 2006

2. Neelesh BodasGuest

LinuxGuy wrote:
> Hi,
>
> I want to add bits to present number. Shift operator pushes bits and
> add '0' at the end.
>
> I want to shift bits and want to add 1 at end

Thats not a quesion regarding standard C++ !!
Anyways, why not just shift left 1 and add 1 ? i.e. f(x) = (x <<1 )+ 1
Or,still faster, shift left 1 and bitwise or with 1 : i.e. f(x) = (x <<
1) | 1

Neelesh Bodas, Jan 16, 2006

3. SharkGuest

> Thats not a quesion regarding standard C++ !!

Thats like saying a "how can I loop 3 times" question doesn't concern
the C++ standard!

Shark, Jan 16, 2006
4. Alf P. SteinbachGuest

* LinuxGuy:
> Hi,
>
> I want to add bits to present number. Shift operator pushes bits and
> add '0' at the end.
>
> I want to shift bits and want to add 1 at end
>
> Ex,
>
> 1)
> suppose Input 0000
> for 1 bit I want output as 0001
>
> 2)
> Input 0100
> for 1 bit output should be
> 1001
>
>
> any help is welcome.

The C++ shift operator is '<<'. Bitwise or is '|'. And there you have
it.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Alf P. Steinbach, Jan 16, 2006
5. Nick KeighleyGuest

Neelesh Bodas wrote:
> LinuxGuy wrote:

> > I want to add bits to present number. Shift operator pushes bits and
> > add '0' at the end.
> >
> > I want to shift bits and want to add 1 at end

>
> Thats not a quesion regarding standard C++ !!
> Anyways, why not just shift left 1 and add 1 ? i.e. f(x) = (x <<1 )+ 1
> Or,still faster, shift left 1 and bitwise or with 1 : i.e. f(x) = (x <<
> 1) | 1

how do you know y = (x << 1) | 1;
is faster than y = = (x << 1) + 1; ?
which implementations did you measure it on?

--
Nick Keighley

Nick Keighley, Jan 16, 2006
6. Mike WahlerGuest

"LinuxGuy" <> wrote in message
news:...
> Hi,
>
> I want to add bits to present number. Shift operator pushes bits and
> add '0' at the end.
>
> I want to shift bits and want to add 1 at end
>
> Ex,
>
> 1)
> suppose Input 0000
> for 1 bit I want output as 0001

unsigned int x(0);
x |= 1;

>
> 2)
> Input 0100
> for 1 bit output should be
> 1001

unsigned int x(4);
x = (x << 1) | 1;

I'm not sure if the parentheses are strictly necessary,
I just used them to ensure order of operations rather
than having to look up precedence rules.

Finally, note that the number of bits used to represent
a given type depends upon the implementation, subject
to minimum requirements, e.g. 'unsigned int' must
have at least 16 bits, but could have more.

-Mike

Mike Wahler, Jan 18, 2006