473,890 Members | 1,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

swapping bytes in an integer

If I have a 32 bit unsigned int that is in the wrong byte order, how
can I convert it? For example, if have a number 0x090a0b0c how can I
reverse this to 0x0c0b0a09 ?

Thanks,
-John

May 8 '06
34 13943

<jo**@fcs.uga.e du> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty. Do you think that it could it be placed
within a #define ?


Yes. Just remember that it's only for 'unsigned long' 's which are 32-bits
in length (i.e., rarely it's non-portable). You'd need a different version
for other unsigned types: short, long long, etc. This method won't work
with signed types.

/* BS for byte-swap */
#define BS(a)
(((a)&0xFF00000 0)>>24)|(((a)&0 xFF0000)>>8)|(( (a)&0xFF00)<<8) |(((a)&0xFF)<<2 4
)

/*...*/
unsigned long a,b;

a=0x090a0b0c;
b=BS(a);
Each 'FF' masks off one of the four respective bytes using the '&' bitwise
and operator. This leaves you with four unsigned long each of which has a
byte to be relocated. The '>>' and '<<' bitshift operators move each byte
to it's new position (within an 'unsigned long'). The '|' bitwise or
operator puts all four unsigned long's, each one with one relocated byte,
back together.

1) four unsigned long's (each 'a')
0x090a0b0
0x090a0b0
0x090a0b0
0x090a0b0

2) and masking, four bytes within unsigned longs
0x09000000
0x000a0000
0x00000b00
0x0000000c

3) shifting, relocated byte within unsigned longs
0x00000009
0x00000a00
0x000b0000
0x0c000000

4) or four together
0x0c0b0a09
This actually optimizes very well with most modern compilers.

It also avoids using byte swapping constructs like arrays or unions which
(in my experience) can cause other programming headaches.
Rod Pemberton
May 10 '06 #21
On 9 May 2006 08:53:26 -0700,
jo**@fcs.uga.ed u <jo**@fcs.uga.e du> wrote
in Msg. <11************ **********@j33g 2000cwa.googleg roups.com>
Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty.
It looks confusing at first, but is simple in reality.
Do you think that it could it be placed
within a #define ?


It could be, but the argument is evaluated four times which will create
trouble if it has side effects. If your macros is called BYTESWAP(a),
then

BYTESWAP(++a) will invoke undefine behavior, and
BYTESWAP(some_f unc(x)) will invoke some_func four times.

Better implement it as an (inline) function.

robert
May 10 '06 #22
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
<jo**@fcs.uga.e du> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty. Do you think that it could it be placed
within a #define ?


Yes. Just remember that it's only for 'unsigned long' 's which are 32-bits
in length (i.e., rarely it's non-portable). You'd need a different version
for other unsigned types: short, long long, etc. This method won't work
with signed types.


I think what he means by "rarely it's non-portable" is "it's
non-portable". unsigned long isn't necessary 32 bits; I regularly use
systems on which it's 64 bits.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
May 10 '06 #23

"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
<jo**@fcs.uga.e du> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty. Do you think that it could it be placed
within a #define ?


Yes. Just remember that it's only for 'unsigned long' 's which are 32-bits in length (i.e., rarely it's non-portable). You'd need a different version for other unsigned types: short, long long, etc. This method won't work
with signed types.


I think what he means by "rarely it's non-portable" is "it's
non-portable". unsigned long isn't necessary 32 bits; I regularly use
systems on which it's 64 bits.


Just because you use a system regularly doesn't mean that it's a non-rare
system. I wouldn't exactly call the Sun-Blade-100's or Cray's you've used
common... In fact, I wouldn't call any mainframe or mini-frame (including
the ones I've used) common.
Rod Pemberton
May 10 '06 #24
Rod Pemberton wrote:
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
<jo**@fcs.ug a.edu> wrote in message
news:11***** *************** **@j33g2000cwa. googlegroups.co m...

Wow! This code is really awesome. I think this is the absolute best
way I have seen yet. I will have to study your code and break it down
to see how it works exaclty. Do you think that it could it be placed
within a #define ?
Yes. Just remember that it's only for 'unsigned long' 's which are
32-bits
in length (i.e., rarely it's non-portable). You'd need a different
version
for other unsigned types: short, long long, etc. This method won't work
with signed types.


I think what he means by "rarely it's non-portable" is "it's
non-portable". unsigned long isn't necessary 32 bits; I regularly use
systems on which it's 64 bits.

Just because you use a system regularly doesn't mean that it's a non-rare
system. I wouldn't exactly call the Sun-Blade-100's or Cray's you've used
common... In fact, I wouldn't call any mainframe or mini-frame (including
the ones I've used) common.

There are a lot of AMD64 and Intel 64 bit systems out here.

--
Ian Collins.
May 10 '06 #25
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
> <jo**@fcs.uga.e du> wrote in message
> news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
>> Wow! This code is really awesome. I think this is the absolute best
>> way I have seen yet. I will have to study your code and break it down
>> to see how it works exaclty. Do you think that it could it be placed
>> within a #define ?
>>
>
> Yes. Just remember that it's only for 'unsigned long' 's which
> are 32-bits in length (i.e., rarely it's non-portable). You'd
> need a different version for other unsigned types: short, long
> long, etc. This method won't work with signed types.


I think what he means by "rarely it's non-portable" is "it's
non-portable". unsigned long isn't necessary 32 bits; I regularly use
systems on which it's 64 bits.


Just because you use a system regularly doesn't mean that it's a non-rare
system. I wouldn't exactly call the Sun-Blade-100's or Cray's you've used
common... In fact, I wouldn't call any mainframe or mini-frame (including
the ones I've used) common.


I didn't say they're non-rare; that's not the point. The point is
that saying "rarely it's non-portable" merely obfuscates the fact that
it's *non-portable*.

64-bit systems are already showing up as home PCs for everyday use,
and they're becoming more and more common.

If you write code that works only on 32-bit systems, it's likely to
work on *most* modern systems. But why waste your time writing code
that works on most systems, when you can write *portable* code with
little additional effort?

All the world was not a VAX 25 years ago, and all the world is not a
32-bit x86 today.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
May 10 '06 #26

"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
> <jo**@fcs.uga.e du> wrote in message
> news:11******** **************@ j33g2000cwa.goo glegroups.com.. .
>> Wow! This code is really awesome. I think this is the absolute best
>> way I have seen yet. I will have to study your code and break it down >> to see how it works exaclty. Do you think that it could it be placed >> within a #define ?
>>
>
> Yes. Just remember that it's only for 'unsigned long' 's which
> are 32-bits in length (i.e., rarely it's non-portable). You'd
> need a different version for other unsigned types: short, long
> long, etc. This method won't work with signed types.

I think what he means by "rarely it's non-portable" is "it's
non-portable". unsigned long isn't necessary 32 bits; I regularly use
systems on which it's 64 bits.
Just because you use a system regularly doesn't mean that it's a non-rare system. I wouldn't exactly call the Sun-Blade-100's or Cray's you've used common... In fact, I wouldn't call any mainframe or mini-frame (including the ones I've used) common.


I didn't say they're non-rare; that's not the point. The point is
that saying "rarely it's non-portable" merely obfuscates the fact that
it's *non-portable*.


Your perspective is what's incorrect. It is portable. It's portable to any
machine which uses 32-bits for 'unsigned long' which is the extreme majority
of architectures in existence. It's _rare_ for an 'unsigned long' to be any
other size even on 16-bit or 64-bit machines. You've attempted to redefine
portability in terms of a few obscure machines.
64-bit systems are already showing up as home PCs for everyday use,
and they're becoming more and more common.

If you write code that works only on 32-bit systems, it's likely to
work on *most* modern systems. But why waste your time writing code
that works on most systems, when you can write *portable* code with
little additional effort?


Since you (claim to) have experience in this area, feel free to post a
portable solution. But, that would violate your personal no-code policy
wouldn't it?
Rod Pemberton
May 11 '06 #27

Rod Pemberton wrote:
"Keith Thompson" <ks***@mib.or g> wrote in message
I didn't say they're non-rare; that's not the point. The point is
that saying "rarely it's non-portable" merely obfuscates the fact that
it's *non-portable*.


Your perspective is what's incorrect. It is portable. It's portable to any
machine which uses 32-bits for 'unsigned long' which is the extreme majority
of architectures in existence. It's _rare_ for an 'unsigned long' to be any
other size even on 16-bit or 64-bit machines. You've attempted to redefine
portability in terms of a few obscure machines.


I think this discussion is overblown. On the one hand, the O/P
specified 32 bit unsigned ints, and the solution you provided is OK
given that spec seems to me. It could add an assert(sizeof(i nt)==4 &&
CHAR_BITS==8) to make sure it isn't misused, but whatever.

On the other hand, the fact that many (at least non-embedded) machines
now use 32 bit ints/longs is not to me relevant. I'd be surprised if
most new desktop/server machines were not 64 bit in the relatively near
future. Writing code, wherever possible, to not care seems entirely
reasonable, unless one is trying to ensure future programming work
upgrading ones source code to be "64 bit safe". This is quite
different (IMHO) than the arguments about whether assuming NULL is all
bits 0 is OK based on the fact that it wasn't in some obsolescent
architectures. I'd go with the pedanticly correct side there too, but
I think it is relatively unlikely that someone will make a new machine
that doesn't treat all bits 0 as NULL. It is a certainty that many new
machines will be released where compilers use long ints that are 64
bits...

-David

May 11 '06 #28
On 2006-05-11, Rod Pemberton <do*********@bi tfoad.cmm> wrote:
Your perspective is what's incorrect. It is portable. It's portable
to any machine which uses 32-bits for 'unsigned long' which is the
extreme majority of architectures in existence. It's _rare_ for an
'unsigned long' to be any other size even on 16-bit or 64-bit
machines. You've attempted to redefine portability in terms of a few
obscure machines.


On what 64-bit machines is unsigned long int a 32-bit type? That's more
rare than for it to be 64 bits.
May 11 '06 #29
"Rod Pemberton" <do*********@bi tfoad.cmm> writes:
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...

[...]
I didn't say they're non-rare; that's not the point. The point is
that saying "rarely it's non-portable" merely obfuscates the fact that
it's *non-portable*.


Your perspective is what's incorrect. It is portable. It's
portable to any machine which uses 32-bits for 'unsigned long' which
is the extreme majority of architectures in existence. It's _rare_
for an 'unsigned long' to be any other size even on 16-bit or 64-bit
machines. You've attempted to redefine portability in terms of a
few obscure machines.


64-bit longs are not rare. 64-bit machines are not obscure. On
64-bit machines, 64-bit longs are much more common than 32-bit longs.
64-bit systems are already showing up as home PCs for everyday use,
and they're becoming more and more common.

If you write code that works only on 32-bit systems, it's likely to
work on *most* modern systems. But why waste your time writing code
that works on most systems, when you can write *portable* code with
little additional effort?


Since you (claim to) have experience in this area, feel free to post a
portable solution. But, that would violate your personal no-code policy
wouldn't it?


Stop trolling, and stop making things up.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
May 11 '06 #30

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

Similar topics

3
2094
by: Christopher Jeris | last post by:
Please help me understand the differences, in semantics, browser support and moral preferredness, between the following three methods of swapping content in and out of a page via JavaScript. I would also appreciate any general criticism you have to offer. I don't know yet how to write the degradation-path code for browsers that don't support the DOM methods I'm using, so there are some commented-out paths below. If the content...
270
3990
by: Jatinder | last post by:
I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
27
4261
by: Daniel Lidström | last post by:
Hello! I want to work with individual bytes of integers. I know that ints are 32-bit and will always be. Sometimes I want to work with the entire 32-bits, and other times I want to modify just the first 8-bits for example. For me, I think it would be best if I can declare the 32-bits like this: unsigned char bits;
8
1937
by: ranjeet.gupta | last post by:
Dear All I am not able o understand the exact number of bytes allocation done by the two fucntion given below, It is said that the fuction Condition_String1 allocates the 240 bytes while Condition_String2 allocates the 72 bytes, I am not able to get the Artimatic Numbers to staisfy the above Number of bytes allocated,
9
1457
by: storyGerald | last post by:
I knew some ways of swapping two ints without using a temporary variable. Just like: // Method 1: void swap1(int &a, int &b) { int temp = a; a = b; b = a; }
34
4870
by: Ann | last post by:
I am opening a file which looks like 0xABCDEF01 on another machine but 0x01EFCDAB on my machine. Is this a byte swapping? Could anyone give a good way to check if bytes are being swapped? (code should work smoothly across different machine.) Thanks, Ann
1
2764
by: spamacon | last post by:
Hello, I have a strange situation using .Net FW 1.1. I want to use Marshal.PtrToStructure to fill the structure below. The first 3 fields get filled correctly: ulStruct describes how big the structure is in bytes (120 bytes, assuming 32-bit IntPtrs), pWmSnapshot gets 0, and usNumWmSnapshots gets 0. The next field, pICView, is a pointer to another structure, and gets filled with some garbage location, which is actually the lower 2 bytes...
11
5495
by: Jiang Nutao | last post by:
Hi, I simplify my problem like below To convert list aa = into How to do it fast? My real list is huge.
8
2054
by: sexauthor | last post by:
I'm converting a VB6 application over that called a 3rd party DLL with specific data structures. The VB6 code defined custom types for those data structures (ie: one with the specific data types, then one as a word array, and one as a byte array, for use in generating CRCs etc) and would LSet one to the other to copy data over. Naturally we can't do that in .NET. I've done lots of reading in the interoperability books and the closest...
0
9980
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
9826
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
9641
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8018
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
5855
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
6061
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4682
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
2
4276
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3283
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.