473,594 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reverse bit order

Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)

Oct 9 '06 #1
20 19776
mi******@gmail. com wrote:
Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)
http://www.google.com/search?hl=en&q=reverse+bits+byte

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 9 '06 #2
mi******@gmail. com wrote:
Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)
No. There is only the hard way ;)
You have to shift the bits one by one.
The best idea is to calculate an array
of 256 values that contain the reversed bits.
Then you can "look up" in that array. Here
is the code to make the array (named "BitField") :

int BitField[256];
for (int i = 0; i < 256; i++)
{
int k = i;
BitField[i] = 0;
for (int b = 0; b < 8; b++)
{
BitField[i] <<= 1;
BitField[i] |= k & 1;
k >>= 1;
}
}

If you want safer code, use a vector instead of an array:
vector<intBitFi eld(256);

Best regards, Martin

P.S. normally, I don't do other people's homework - SCNR this time ;)
Oct 10 '06 #3
Mike posted:
Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)

Here's some code I wrote last month. It's written in C, but you'll get the
idea:

http://groups.google.ie/group/comp.l...473fb7f?hl=en&

--

Frederick Gotham
Oct 10 '06 #4
Martin Steen wrote:
>
int BitField[256];
for (int i = 0; i < 256; i++)
{
int k = i;
BitField[i] = 0;
for (int b = 0; b < 8; b++)
{
BitField[i] <<= 1;
BitField[i] |= k & 1;
k >>= 1;
}
}

If you want safer code, use a vector instead of an array:
vector<intBitFi eld(256);
How is that safer? Either way looks equally correct. If you're worried
about typos, it's far better to use a manifest constant instead of that
hardcoded value of 256.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Oct 10 '06 #5
Martin Steen wrote:
mi******@gmail. com wrote:
>Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)

No. There is only the hard way ;)
If there are only 8 bits in a byte (and nobody said it was the actual
requirement), then a table of 255 values would be the easiest way.

if (mybyte)
mybyte = mytable[mybyte];

Now, generation of the table can be done once, outside of your program.
[..code not involving a table redacted..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 10 '06 #6
mi******@gmail. com wrote:
Is there any easy way to reverse the order of the bits in a byte in
C++?

(i.e. 00000001 becomes 10000000)
The one true way is to recognize that reversing any sequence of bits
involves only splitting it into two parts and returning a value whose
upper half is the reverse of the original lower half and whose lower
half is the reverse of the original upper half. Like this:

#include <limits>
#include <iomanip>
#include <iostream>
using std::numeric_li mits;
using std::cout; using std::hex; using std::showbase;
using std::internal; using std::setw;

template <unsigned nstruct reverser_imp
{
static inline unsigned reverse(unsigne d val, unsigned mask)
{
mask >>= (n/2);
return reverser_imp<n/2>::reverse((va l >(n/2)) & mask, mask)
| (reverser_imp<n/2>::reverse(va l & mask, mask) << (n/2));
}
};

template <struct reverser_imp<1>
{
static inline unsigned reverse(unsigne d val, unsigned)
{
return val;
}
};

inline unsigned reverse(unsigne d val)
{
return reverser_imp<nu meric_limits<un signed char>::digits>: :
reverse(val, numeric_limits< unsigned char>::max());
}

void show_reversed(u nsigned val)
{
cout.fill('0');
cout << hex << showbase << internal;
cout << setw(4) << val << ": "
<< setw(4) << reverse(val) << '\n';
}
int main()
{
show_reversed(0 x0f);
show_reversed(0 x80);
show_reversed(0 x40);
show_reversed(0 xC0);
return 0;
}
--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Oct 10 '06 #7
Pete Becker posted:
inline unsigned reverse(unsigne d val)
{
return reverser_imp<nu meric_limits<un signed char>::digits>: :
reverse(val, numeric_limits< unsigned char>::max());
}

In my opinion, it's major overkill to use either of:

numeric_limits< char unsigned>::digi ts
numeric_limits< char unsigned>::max

The former can be retrieved from:

CHAR_BIT

, while the latter can be retrieved from:

(char unsigned)-1

or even:

UCHAR_MAX

--

Frederick Gotham
Oct 10 '06 #8
Frederick Gotham wrote:
Pete Becker posted:
>inline unsigned reverse(unsigne d val)
{
return reverser_imp<nu meric_limits<un signed char>::digits>: :
reverse(val, numeric_limits< unsigned char>::max());
}


In my opinion, it's major overkill to use either of:

numeric_limits< char unsigned>::digi ts
numeric_limits< char unsigned>::max

The former can be retrieved from:

CHAR_BIT

, while the latter can be retrieved from:

(char unsigned)-1

or even:

UCHAR_MAX
Haven't you gotten the word? Macros are evil. This is the 21st century.
Quaint C approaches should never be used. Templates, templates,
templates. Always.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Oct 10 '06 #9
Pete Becker posted:
Haven't you gotten the word? Macros are evil. This is the 21st century.
Quaint C approaches should never be used. Templates, templates,
templates. Always.
Exceptions, exceptions, exception -- and not the kind you throw!

C++ has many "warts" (if you wish to call them that) which perpetuate from
its origins in C. We have accepted these warts, documented them, and moved
forward.

When you want to give something a name in C++ (be it a function, an object,
a class), then you don't need to pick a very unique name, because all you
need do is enclose it in a namespace:

namespace MyNamespace { int cout; }

Macros muck this up completely. However, there is a finite list of macros
which the Standard defines, such as:

INT_MAX
UCHAR_MAX
CHAR_BIT

As always, the Standard can take liberties wherever it pleases, and it
chooses to define these macros. If you genuinely perfer the numeric_limits
method, then go ahead. However, I myself find it awfully tedious and
longwinded, and I prefer good ol' CHAR_BIT.

While one should hesitate to define macros (for the obvious reasons),
there's no need to hesitate to use the ones that are already there, and
which will _always_ be there. Never will we be able to write:

int CHAR_BIT = 5;

Also, you might notice that "max" and "min" don't evaluate to a compile-
time constant, which make INT_MAX and the like all the more attractive.

--

Frederick Gotham
Oct 10 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
3721
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ------------------------------------------------------------- PEP: 323
3
3377
by: R. Rajesh Jeba Anbiah | last post by:
Unfortunately, I couldn't find any way to traverse the object array in reverse order. I'd thought there must be a way to do it with for..in loop, but couldn't find anything yet. Could someone please help me? TIA. -- <?php echo 'Just another PHP saint'; ?> Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/
14
14758
by: ford_desperado | last post by:
Why isn't ALLOW REVERSE SCANS the default? Why do we have to - drop PK - create an index - recreate PK What are the advantages of indexes that do not allow reverse scans?
6
6457
by: Zri Man | last post by:
I'm relatively new to DB2 and was reasonably amused to see the REVERSE SCAN availability for Indexes. My assumptions are as follows: DB2/UDB uses B-Tree for indexing by default and is likely the main offering for Indexing within the DB. Reverse Scans could possibly only happen on the the leaf node of the index
20
33026
by: sahukar praveen | last post by:
Hello, I have a question. I try to print a ascii file in reverse order( bottom-top). Here is the logic. 1. Go to the botton of the file fseek(). move one character back to avoid the EOF. 2. From here read a character, print it, move the file pointer (FILE*) to 2 steps back (using fseek(fp, -2, SEEK_CUR)) to read the previous character. This seems to be ok if the file has a single line (i.e. no new line character). The above logic...
19
13562
by: RAJASEKHAR KONDABALA | last post by:
Hi, Does anybody know what the fastest way is to "search for a value in a singly-linked list from its tail" as oposed to its head? I am talking about a non-circular singly-linked list, i.e., head and tail are not connected. Of course, recursive function aproach to traverse the list is one way. But, depending upon the list size, it could overrun the stack pretty fast.
10
2190
by: OtisUsenet | last post by:
Hello, I am trying to select distinct dates and order them in the reverse chronological order. Although the column type is TIMESTAMP, in this case I want only YYYY, MM, and DD back. I am using the following query, but it's not returning dates back in the reverse chronological order: SELECT DISTINCT
10
5365
by: aatish19 | last post by:
1: Write a program that asks the user to input an integer value and print it in a reverse order Sample Output Enter any number 65564 Reverse of 65564 is 46556 2: Write a program that takes a string as an input and print it in reverse order.(don't use bulit-in/library function). Sample Output Enter any string: i m Kashif
40
36452
by: KG | last post by:
Could any one tell me how to reverse the bits in an interger?
0
7946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7877
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8253
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
5739
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5411
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3867
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2389
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.