Can anyone help me to explain me the small code snippet below?

Posted on 2006-11-14
Medium Priority
Last Modified: 2010-04-15
Can anyone help me to explain the following code snippet.This program is used to convert  bits from Big endian to little endian.What is CHAR_BIT?It has not been declared anyewhere and what right takes as a paramater.If possible can you explain the below lines with a small example.

#include <limits.h>
unsigned unsigned int reversebytes(unsigned int right) // Please write your comments here.
  int left=0;
  int i;
  for( i=0;i<sizeof(int); i++ ){
    left <<= CHAR_BIT; //
    left += right&(1<<CHAR_BIT)-1; //
    rignt >>= CHAR_BIT; //
  return left;

 Eagerly waiting for the reply.
Question by:tatikor_143
  • 5
  • 3
  • 3

Expert Comment

ID: 17942052
This isn't a well written function. I will let you discover the error here.

Let's do a walk through and start with some assumptions.

1) let us assume that sizeof(int) = 4 (32 bits).
2) CHAR_BIT appears to be number of bits in a char (8).
3) The object here looks like it will input ABCD and return DCBA.

Each loop will take one group of CHAR_BIT (8) bits out of right and place it into left.

It prepares for the next iteration by shifting the remaining bits in right down 8 bits and shifting the value in left up by 8 bits.
You will see right and left looking like:
right    |  left
ABCD | ----
-ABC   | ---D
--AB    | --DC
---A      | -DCB
----       | DCBA
After i reaches sizeof(int), the value in left is returned.

right has no arguments as it is itself an argument.

Can you see the mistake in this function?


Author Comment

ID: 17942569
Hi Bill,

I am sorry to say that I am still confused.I am bit poor in bitwise programming.Can you please explain me the above one with small program.

Suppose if I give value as 10.How it will be stored in Big endian format and little endian format and how the bits are swapped from the above program?

A prompt response is highly appreciated.

Thanks in advance
LVL 85

Expert Comment

ID: 17942587
CHAR_BIT as defined in limits.h is the number of bits for the smallest object that is not a bitfield in your implementatiion
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 85

Expert Comment

ID: 17942610
the number 10 in binary is 1010
if a 16 bit value is stored in two 8 bit bytes,
it will be either
00000000 00001010
if the high order byte comes first (bigendian) or
00001010 00000000
if the low order byte comes first (littleendian)

Accepted Solution

billtouch earned 2000 total points
ID: 17944726
A small program is what you have presented. Let me try to help you understand it better.

In c, the << and >> are bitwise operators. The statement: a << b causes the value in a to be shifted left by b bytes.

a = 00000010;
b = 2;

c = a << b;

then c will contain the value: 00001000;

You will notice the bit has moved two places to the left. The value of c is a * 2 to the bth power ( a( 2^b) ).

With the >> operator, the bit will move to the right.

If a bit is on the edge (left edge for << or right edge for >>), it will be shifted out and lost. Zeros are shifted into the opposite end.
so if you had a 16 bit integer shifted in either direction 16 bits, the value left in that integer will be zero.

char c;  // An 8 bit integer

c = 0xFF // binary 11111111
for ( i=0; i<8; i++ )
  c  << 1;
  printf( "%x\n", c ;

will print:
7f                     ( 0111 1111 )
3f                     ( 0011 1111 )
1f                     ( 0001 1111 )
0f                     ( 0000 1111 )
07                    ( 0000 0111 )
03                    ( 0000 0011 )
01                    ( 0000 0001 )
00                    ( 0000 0000 )

Do you see how the bitwise operators work now?

Then take that and expand it to a 32 bit word and instead of shifting left or right one bit, you shift one byte or 8 bits. Now you have how your model works.

By the way... the bug in your example is not in the bitwise manipulations. Try to figure it out. It is a common c mistake.



Expert Comment

ID: 17947193
Ok - I just reread this when I was awake. In the code snipit I gave, the "c << 1;" should be  "c>>=1;".


Author Comment

ID: 17947952
Hi Bill,

Thanks for the detailed explanation on the bitwise operators.Now I am compleately aware of the logic used in the above programb but there is a small mistake in the above one.I guess it is

1) left += right&(1<<CHAR_BIT)-1 // -1 should be placed inside the brackets so that it evaluates to 255 and become 11111111 so that it swap the bytes to the left with the same value.

Please let me know if I am right.


Expert Comment

ID: 17951145
Actually, that is correct. It would have been less cryptic if it were in parenthesis.

left += right&(1<<CHAR_BIT)-1

First notice the &. Since you are dealing with 8 bit bytes, you would want to mask off the lower 8 bits of right. So you would write
(right & 0xff).
This is written to accomodate a variable byte size (almost never  heard of anymore).
In all machines that  have 8 bit bytes the value of CHAR_BIT is 8. Thus the expression (1<<CHAR_BIT) is (1<<8) or 0x100.
You want this to be a mask so you subtract one and you get your 0xff.
So that expression is equivalent to (right & 0xff). Putting the -1 in brackets would give different results.

That is not the error. I might add that there is a syntax error as well (unsigned unsigned).

The error is: int left. The function takes in an unsigned and returns an unsigned, both 32 bits of significance and uses a signed left with 31 bits of significance. That makes a difference because they use an += instead of a |=.

LVL 85

Expert Comment

ID: 17951287
+= won't  be a problem with a signed int, but the <<= could be
It looks like one of the 'unsigned' qualifiers got moved from where it was supposed to be.

Expert Comment

ID: 17951403
You are right - I missppoke there. After I posted the last remark it dawned on me that the misplaced unsigned was probably a victim of being copied.

But using a bitwise operator (|= ) is more appropriate than an arithmetic operator (+=) in this context.


Author Comment

ID: 17951686
Thanks bill,for your support.

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question