Solved

How to swap Four bytes ?

Posted on 2014-03-18
13
263 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
Comment Utility
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
Comment Utility
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:Bing CISM / CISSP
Comment Utility
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
 
LVL 86

Expert Comment

by:jkr
Comment Utility
>>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:Bing CISM / CISSP
Comment Utility
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
 

Author Comment

by:naseeam
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:naseeam
Comment Utility
After swapping, it should be 0x03000000
0
 
LVL 86

Expert Comment

by:jkr
Comment Utility
Too much casting IMO - just try

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

Open in new window

0
 

Author Comment

by:naseeam
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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:Bing CISM / CISSP
Bing CISM / CISSP earned 150 total points
Comment Utility
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
 

Author Closing Comment

by:naseeam
Comment Utility
Great support.  Provided solution and debugged the problem.

Excellent portability tip.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now