Is there any easy way to reverse the order of the bits in a byte in
C++?
(i.e. 00000001 becomes 10000000) 20 19737 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<intBitField(256);
Best regards, Martin
P.S. normally, I don't do other people's homework - SCNR this time ;)
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
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<intBitField(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.
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 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_limits;
using std::cout; using std::hex; using std::showbase;
using std::internal; using std::setw;
template <unsigned nstruct reverser_imp
{
static inline unsigned reverse(unsigned val, unsigned mask)
{
mask >>= (n/2);
return reverser_imp<n/2>::reverse((val >(n/2)) & mask, mask)
| (reverser_imp<n/2>::reverse(val & mask, mask) << (n/2));
}
};
template <struct reverser_imp<1>
{
static inline unsigned reverse(unsigned val, unsigned)
{
return val;
}
};
inline unsigned reverse(unsigned val)
{
return reverser_imp<numeric_limits<unsigned char>::digits>::
reverse(val, numeric_limits<unsigned char>::max());
}
void show_reversed(unsigned val)
{
cout.fill('0');
cout << hex << showbase << internal;
cout << setw(4) << val << ": "
<< setw(4) << reverse(val) << '\n';
}
int main()
{
show_reversed(0x0f);
show_reversed(0x80);
show_reversed(0x40);
show_reversed(0xC0);
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.
Pete Becker posted:
inline unsigned reverse(unsigned val)
{
return reverser_imp<numeric_limits<unsigned char>::digits>::
reverse(val, numeric_limits<unsigned char>::max());
}
In my opinion, it's major overkill to use either of:
numeric_limits<char unsigned>::digits
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
Frederick Gotham wrote:
Pete Becker posted:
>inline unsigned reverse(unsigned val) { return reverser_imp<numeric_limits<unsigned char>::digits>:: reverse(val, numeric_limits<unsigned char>::max()); }
In my opinion, it's major overkill to use either of:
numeric_limits<char unsigned>::digits
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.
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
Frederick Gotham wrote:
>
Macros muck this up completely.
Yup. They're evil. Doesn't matter how you rationalize it.
[rationalizaton snipped]
It's far better to write long winded, unmaintainable, compiler-busting
templates than to resort to macros. That's the C++ way!
--
-- Pete
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see www.petebecker.com/tr1book.
Pete Becker posted:
Frederick Gotham wrote:
>> Macros muck this up completely.
Yup. They're evil. Doesn't matter how you rationalize it.
[rationalizaton snipped]
So _your_ rationalisation is this:
There's a undamaged wheel in a car-wreck, but we can't make use of it
because it's evil for a car to crash.
It's far better to write long winded, unmaintainable, compiler-busting
templates than to resort to macros. That's the C++ way!
Indeed it is, but not when it comes to the most basic of things, and there
is little more basic than the CHAR_BIT family of macros. Even if you choose
to never us CHAR_BIT and the like, you'll never be able to write:
namespace MyNamespace { int CHAR_BIT(); }
well... not in your header files in anyway.
--
Frederick Gotham
Frederick Gotham wrote:
Pete Becker posted:
>It's far better to write long winded, unmaintainable, compiler-busting templates than to resort to macros. That's the C++ way!
Indeed it is,
Now you've seen the light.
but not when it comes to the most basic of things, and there
is little more basic than the CHAR_BIT family of macros. Even if you choose
to never us CHAR_BIT and the like, you'll never be able to write:
namespace MyNamespace { int CHAR_BIT(); }
well... not in your header files in anyway.
That's because macros are evil. Always use templates. Never use macros.
If you can't write it as a template you haven't tried hard enough.
--
-- Pete
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see www.petebecker.com/tr1book.
Pete Becker posted:
That's because macros are evil. Always use templates. Never use macros.
If you can't write it as a template you haven't tried hard enough.
This has nothing to do with "Writing Templates" Vs "Writing Macros", and
everything to do with the Standard Library, which provides certain macros.
There's plenty of things you can do with macros which you _can't_ do with
templates.
--
Frederick Gotham
Frederick Gotham wrote:
Pete Becker posted:
That's because macros are evil. Always use templates. Never use macros.
If you can't write it as a template you haven't tried hard enough.
This has nothing to do with "Writing Templates" Vs "Writing Macros", and
everything to do with the Standard Library, which provides certain macros.
There's plenty of things you can do with macros which you _can't_ do with
templates.
Hey Fred, so that the rest of us can sleep easy, could you please post
something acknowledging that you knew that each of Pete's postings in
this subthread regarding templates vs. macros has been tongue-in-cheek.
Your responses have appeared to take Pete seriously, and perhaps you
have done so just to be funny, but if so I must confess that your humor
is sometimes over my head.
Best regards,
Tom
Thomas Tutone posted:
Hey Fred, so that the rest of us can sleep easy, could you please post
something acknowledging that you knew that each of Pete's postings in
this subthread regarding templates vs. macros has been tongue-in-cheek.
Your responses have appeared to take Pete seriously, and perhaps you
have done so just to be funny, but if so I must confess that your humor
is sometimes over my head.
I had no reason to think Pete was being sarcastic.
Maybe I'm a bit socially retarded today. . . or maybe I'm just used to the
wide variety of people (and therefore attitudes) I encounter on Usenet.
--
Frederick Gotham
Frederick Gotham wrote:
Pete Becker posted:
>That's because macros are evil. Always use templates. Never use macros. If you can't write it as a template you haven't tried hard enough.
This has nothing to do with "Writing Templates" Vs "Writing Macros", and
everything to do with the Standard Library, which provides certain macros.
It's about writing code to reverse the bits in a byte. Don't you remember?
>
There's plenty of things you can do with macros which you _can't_ do with
templates.
If you can't do it with templates you shouldn't be doing it.
--
-- Pete
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see www.petebecker.com/tr1book.
"Pete Becker" <pe********@acm.orgwrote in message
news:QM******************************@giganews.com ...
Frederick Gotham wrote:
>Pete Becker posted:
>>It's far better to write long winded, unmaintainable, compiler-busting templates than to resort to macros. That's the C++ way!
Indeed it is,
Now you've seen the light.
>but not when it comes to the most basic of things, and there is little more basic than the CHAR_BIT family of macros. Even if you choose to never us CHAR_BIT and the like, you'll never be able to write:
namespace MyNamespace { int CHAR_BIT(); }
well... not in your header files in anyway.
That's because macros are evil. Always use templates. Never use macros. If
you can't write it as a template you haven't tried hard enough.
So tell me, do you use header guards?
Frederick Gotham wrote:
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;
what about :
#undef CHAR_BIT
int CHAR_BIT = 5;
or is that Undefined Behavior?
Nate
Nate Barney wrote:
Frederick Gotham wrote:
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;
what about:
#undef CHAR_BIT
int CHAR_BIT = 5;
or is that Undefined Behavior?
Hahaha... it never stops, does it? :)
Jim Langston wrote:
"Pete Becker" <pe********@acm.orgwrote in message
news:QM******************************@giganews.com ...
>Frederick Gotham wrote:
>>Pete Becker posted:
It's far better to write long winded, unmaintainable, compiler-busting templates than to resort to macros. That's the C++ way!
Indeed it is,
Now you've seen the light.
>>but not when it comes to the most basic of things, and there is little more basic than the CHAR_BIT family of macros. Even if you choose to never us CHAR_BIT and the like, you'll never be able to write:
namespace MyNamespace { int CHAR_BIT(); }
well... not in your header files in anyway.
That's because macros are evil. Always use templates. Never use macros. If you can't write it as a template you haven't tried hard enough.
So tell me, do you use header guards?
Never. Header guards are for wimps. If you can't get your #include
directives right, you shouldn't be writing code.
--
-- Pete
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see www.petebecker.com/tr1book. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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
...
|
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...
|
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?
|
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...
|
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....
|
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.,...
|
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...
|
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...
|
by: KG |
last post by:
Could any one tell me how to reverse the bits in an interger?
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |