Solved

How to swap Four bytes ?

Posted on 2014-03-18
13
273 Views
Last Modified: 2014-03-19
virtual ParameterResult setValueRaw    (const char * val, unsigned short size, bool force = false) 
    {
        if (size == LONG_SIZE)
        {
           char *tv = new char[size];
      
           tv[0] = val[2];
           tv[1] = val[3];
           tv[2] = val[0];
           tv[3] = val[1];
      
           ParameterLong::setValue(tv, size, force);
			
           delete[] tv;
			}
          return getResultId();                                                      
    }

Open in new window


Above is how I did it.  Please share a better solution ?

We use Keil tools.  We write code for NXP LPC2468 ARM 7 Microcontroller.

Most Significant word is      00 01
Leastg Significant Word is   00 05

Example, val will be pointing to four bytes as follows:
01 00 05 00

After running the function:
05 00 01 00
0
Comment
Question by:naseeam
  • 6
  • 4
  • 3
13 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 39938035
This is pretty much the same that 'htonl()'/'ntohl()' perform. You can implement that using a macro, i.e.

#define SWAP_BYTES(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))

Open in new window

0
 
LVL 86

Expert Comment

by:jkr
ID: 39938052
Ooops, forgot to add an example:

#define SWAP_BYTES(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))

virtual ParameterResult setValueRaw    (const char * val, unsigned short size, bool force = false) 
    {
        if (size == LONG_SIZE)
        {
           long l = SWAP_BYTES((long) val);
      
           ParameterLong::setValue((char*) l, size, force);
			
           
	}

          return getResultId();                                                      
    }
                          

Open in new window

0
 
LVL 37

Expert Comment

by:bbao
ID: 39938062
just right shift the four-byte LONG WORD variable for 16 bits.

see below for the details.

FYI - Left Shift and Right Shift Operators (>> and <<)
http://msdn.microsoft.com/en-us/library/336xbhcz.aspx
0
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 86

Expert Comment

by:jkr
ID: 39938074
>>just right shift the four-byte LONG WORD variable for 16 bits.

Yes, that's exactly what my example does ;o)
0
 
LVL 37

Expert Comment

by:bbao
ID: 39938128
sorry, i posted from mobile and didn't see your previous comment. you must be posting it when i was typing slowly on the phone. :-)
0
 
LVL 1

Author Comment

by:naseeam
ID: 39938403
Macro you provided looks correct to me.  I must be doing something wrong.  Please help debug.

#define SWAP_WORDS(n) (((((long)(n) & 0xFFFF)) << 16) | (((long)(n) & 0xFFFF0000) >> 16))

Open in new window



 virtual ParameterResult setValueRaw            (const char * val, unsigned short size, bool force = false) 
    {
			if (size == LONG_SIZE)
			{
        long l = SWAP_WORDS( (long)(*((long *)val)) );
            
        ParameterLong::setValue((char *)l, size, force);
			}
      return getResultId();                                                      
    }

Open in new window


I pass 0x00000300 to this function.  value of l is  0x00000003.  That's incorrect!
0
 
LVL 1

Author Comment

by:naseeam
ID: 39938417
After swapping, it should be 0x03000000
0
 
LVL 86

Expert Comment

by:jkr
ID: 39938419
Too much casting IMO - just try

           long l = SWAP_BYTES((long) val);
      
           ParameterLong::setValue((char*) l, size, force);

Open in new window

0
 
LVL 1

Author Comment

by:naseeam
ID: 39938447
>> long l = SWAP_BYTES((long) val);

but val is pointer.  If you pass val, then address will be swapped.  We need to swap what val points to.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39938458
I took that into account, try it ;o)

It is a pointer, but will be treated as an integer for swapping. Then later, it is cast back to a pointer.
0
 
LVL 86

Accepted Solution

by:
jkr earned 350 total points
ID: 39938467
Ooops, sorry, I see what you mean - in that case, try

           long l = SWAP_BYTES(*((long*) val));
      
           ParameterLong::setValue((char*) &l, size, force);

Open in new window

0
 
LVL 37

Assisted Solution

by:bbao
bbao earned 150 total points
ID: 39938572
IMHO, from a perspective of professional programming, it is NOT a good practice to use a LONG WORD variable for calculating a pointer, as the code will be highly processor, platform and compiler dependent. maintainIng this kind of code could be very difficult, as compiling the same code with different compiler or with different processor may cause different result, hence calling the pointer or using the pointed data may cause unexpected software behaviour.

commonly, as a best practice, pointers should be always managed by pointer variables, not converted from numbers even something like LONG WORD. a pointer's value should not be calculated that way except the compuation is under control such as that for string operations.

however, if for some reasons a processor specific pointer calculation is really necessary, e.g. for a kernel routine of memory management, preprocessor directives and conditional compilation directives are required at the beginning of source code to control the compiling and building process in order to make the result consistent and of course correct.
0
 
LVL 1

Author Closing Comment

by:naseeam
ID: 39939588
Great support.  Provided solution and debugged the problem.

Excellent portability tip.
0

Featured Post

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!

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

679 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