Want to shift bits with addition of 1

L

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.

Thanks
 
N

Neelesh Bodas

LinuxGuy said:
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
 
S

Shark

Thats not a quesion regarding standard C++ !!

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

Alf P. Steinbach

* 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.
 
N

Nick Keighley

Neelesh said:
LinuxGuy wrote:

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?
 
M

Mike Wahler

LinuxGuy said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top