473,809 Members | 2,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Endianess...

Hi,
I thought I understood this stuff - but...

This little program (taken from W. Richard Stevens Unix Network
Programming Volume 1) determines a machine's endianess:

#include <iostream>
using namespace std;

int main()
{
union {
unsigned short us;
char c[sizeof(unsigned short)];
} un;

un.us = 0x1234;

if (sizeof(unsigne d short) == 2) {
if (un.c[0] == 0x12 && un.c[1] == 0x34)
cout << "big-endian\n";
else if (un.c[0] == 0x34 && un.c[1] == 0x12)
cout << "little-endian\n";
else
cout << "unknown\n" ;
} else
cout << "sizeof(unsigne d short) = " << sizeof(unsigned short)
<< ".\n";
}

On my machine it prints little-endian (as expected). This obviously
must mean that the bits are laid out in memory as: "0x34, 0x12". Right?

So if I want to send an unsigned short over the network from this
machine (which should be done in network byte-order/big-endian) I must
convert the order of the bytes in memory so this unsigned short is sent
as "0x12, 0x34". Right? (Oh, btw I do not have htons on this platform
:-( ... )

Now the following short block of code converts the unsigned short into
a stream of two bytes:

// Remember: stored in memory as 0x34 0x12
unsigned short us = 0x1234;

char buf[2];

// Convert from little-endian to big endian
buf[0] = us & 0xFF; // Should now contain 0x12
buf[1] = (us >> 8) & 0xFF; // Should now contain 0x34

// Print the stream...
printf("0x%.2X" , buf[0]);
printf(", ");
printf("0x%.2X" , buf[1]);
printf("\n");

To my great surprise it printed:
0x34, 0x12

What?!?!?!?

If I change to:
buf[0] = (us >> 8) & 0xFF;
buf[1] = us & 0xFF;
everything works OK but I think it should not! Sigh...
Please enlight me!

/Pelle

Jul 23 '05 #1
4 1963
pe************@ yahoo.com wrote:
[...]
// Remember: stored in memory as 0x34 0x12
That means that 0x34 has *lower* address than 0x12.
unsigned short us = 0x1234;

char buf[2];

// Convert from little-endian to big endian
buf[0] = us & 0xFF; // Should now contain 0x12
Why? (0x1234 & 0x00ff) gives 0x34.
buf[1] = (us >> 8) & 0xFF; // Should now contain 0x34
Why? (0x1234 >> 8) gives 0x12.
// Print the stream...
printf("0x%.2X" , buf[0]);
printf(", ");
printf("0x%.2X" , buf[1]);
printf("\n");

To my great surprise it printed:
0x34, 0x12

What?!?!?!?

If I change to:
buf[0] = (us >> 8) & 0xFF;
buf[1] = us & 0xFF;
everything works OK but I think it should not! Sigh...
Please enlight me!


Write down what the bit patterns look like and perform shifts and ANDs.

Victor
Jul 23 '05 #2
Victor Bazarov wrote:
pe************@ yahoo.com wrote:
[...]
// Remember: stored in memory as 0x34 0x12

That means that 0x34 has *lower* address than 0x12.
unsigned short us = 0x1234;

char buf[2];

// Convert from little-endian to big endian
buf[0] = us & 0xFF; // Should now contain 0x12

Why? (0x1234 & 0x00ff) gives 0x34.


Wanted to add: "...regardl ess of endianness."
buf[1] = (us >> 8) & 0xFF; // Should now contain 0x34

Why? (0x1234 >> 8) gives 0x12.


regardless of endianness, again.
[...]

Jul 23 '05 #3
pe************@ yahoo.com wrote:
Hi,
I thought I understood this stuff - but...


I'm not sure what you want but this is a post in an earlier thread that
might give you some ideas.

http://groups-beta.google.com/group/...a?dmode=source
Jul 23 '05 #4

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:gs******** **********@news read1.mlpsca01. us.to.verio.net ...
Victor Bazarov wrote:
pe************@ yahoo.com wrote:
[...]
// Remember: stored in memory as 0x34 0x12

That means that 0x34 has *lower* address than 0x12.
unsigned short us = 0x1234;

char buf[2];

// Convert from little-endian to big endian
buf[0] = us & 0xFF; // Should now contain 0x12

Why? (0x1234 & 0x00ff) gives 0x34.


Wanted to add: "...regardl ess of endianness."
buf[1] = (us >> 8) & 0xFF; // Should now contain 0x34

Why? (0x1234 >> 8) gives 0x12.


regardless of endianness, again.
[...]


Hi Pelle

Just in case it wasn't clear to you what Victor was saying: when you
shift bits like that, you don't have to worry about what the order of bytes
in the physical memory is. Just treat it like you would on paper. Shifting
to the right, for example, will shift the high-order bits towards the
low-order side, and it does not matter whether the low-order byte is stored
in a higher or lower location in physical memory. So, using your example,
doing 0x1234 >> 8 will always result in 0x0012, and never in 0x3400,
reagardless of the machine's byte ordering.

You only really need to worry about byte ordering when reading values
from a data stream on a machine that has one ordering when that data was
written using the opposite ordering.

(What our software does is use a compile flag that, when compiling for
the PC, byte ordering is intentionally reversed when reading or writing, so
that we know it will match what's done on the Mac. When compiled on the
Mac, reading and writing is done without changing the ordering. We use
#defines and #ifdefs to determine whether to call the order-reversing code
or not.)

-Howard

Jul 23 '05 #5

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

Similar topics

6
14778
by: hantheman | last post by:
Is this a portable implementation? #if defined(BIG_ENDIAN) && !defined(LITTLE_ENDIAN) #define htons(A) (A) #define htonl(A) (A) #define ntohs(A) (A) #define ntohl(A) (A) #elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
5
5511
by: SpOiLeR | last post by:
Hi. q1: Is std::bitset<N> part of standard or it's compiler extension? q2: Is std::bitset::to_string() part of standard? q3: My documentation say this about std::bitset::to_string(): "...each character is 1 if the corresponding bit is set, and 0 if it is not. In general, character position i corresponds to bit position N - 1 -
4
3477
by: Gernot Frisch | last post by:
Hi, does the ARM processors have different endians than x86 platform? For ints and/or floating points??? I get a really strange objec when loading it from a file. Creating manually works. -- -Gernot
8
4089
by: | last post by:
Well! Maybe I wrote this word incorrect but its not included im my e-dictionary! I have a structure with many int, short etc I execute this function: fread(&my_struct, sizeof(struct), 1, filepointer); The problem is this: In different endianess platforms from same file will be loaded different data in the class.
12
1651
by: Oliver Knoll | last post by:
Ok, I've searched this group for Big/Little endian issues, don't kill me, I know endianess issues have been discussed a 1000 times. But my question is a bit different: I've seen the follwing function several times, it converts data stored in Big Endian (BE) format into host native format (LE on LE machines, BE on BE machines):
1
3158
by: mathieu | last post by:
Hello, I am working on a project where I need to serialize my objects to a stream in a mixed ASCII/binary way. Using the c++ iostream was extremely straighforward and I quickly made progress. Unfortunately I need to handle endianess (reading big endian binary file on little endian architecture and vice versa). In order to do that I copy paste a hierachy-like structure for my own IOStream. Basically I have (*) All I need to do then is to...
0
9721
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
9601
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
10637
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10379
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10115
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9199
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...
0
5550
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
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.