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

Home Posts Topics Members FAQ

Endianess: why does this code not change value on BE machine?

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):

/* - this code swaps the bytes on a Little Endian Machine
- this code returns 'data' unmodified on a Big Endian Machine.
*/
static short getShortBE (char *data)
{
return (short) ((data[0] << 8) | data[1]);
}

I can understand why this function swaps bytes on a LE machine, but
why doesn't it alter 'data' on a BE machine? I've tried to understand
it with diagrams and everything, but my brain went just crazy! Can
anyone give me a simple explanation please? :) I'm really curious...

And how would a function look like which does the "opposite": swap
bytes on a BE machine, don't change values on a LE machine (that is,
"read and convert LE data")? :) Hope I can answer the 2nd quesion
myself when I understand the 1st question... :)
Here's the complete test program:

#include <stdlib.h>
#include <stdio.h>

/* This function is useful when reading and converting data which is
stored
in Big Endian Format.
- this code swaps the bytes on a Little Endian Machine
- this code returns 'data' unmodified on a Big Endian Machine.
*/
static short getShortBE (char *data)
{
return (short) ((data[0] << 8) | data[1]);
}

int main (int argc, char **argv)
{
int a;
char c;
short data1;
short data2;
char *d;

(void)argc;
(void)argv;

a = 0x01020304;
c = ((char *)&a)[0];

if (c == 1)
{
fprintf (stdout, "Integer a: %x - first byte: %x (MSB) -> Big
endian machine.\n", a, c);
}
else if (c == 4)
{
fprintf (stdout, "Integer a: %x - first byte: %x (LSB) -> Little
endian machine.\n", a, c);
}
else
{
fprintf (stdout, "Integer a: %x - first byte: %x -> A weirdo
machine.\n", a, c);
}

data1 = 0x0102;
d = ((char *)&data1);

fprintf (stdout, "Data[0]: %x - Data[1]: %x\n",
*d, *(d + 1));

data2 = getShortBE ((char *)&data1);

d = ((char *)&data2);
fprintf (stdout, "After GET: Data[0]: %x - Data[1]: %x\n",
*d, *(d + 1));

return 1;
}

Output:
-------

On Sun:
./Endian

Integer a: 1020304 - first byte: 1 (MSB) -> Big endian machine.
Data[0]: 1 - Data[1]: 2
After GET: Data[0]: 1 - Data[1]: 2

On Linux (i386):

Integer a: 1020304 - first byte: 4 (LSB) -> Little endian machine.
Data[0]: 2 - Data[1]: 1
After GET: Data[0]: 1 - Data[1]: 2

Thanks, Oliver
Nov 14 '05
12 1651
Oliver Knoll wrote:
...
/* - this code swaps the bytes on a Little Endian Machine
- this code returns 'data' unmodified on a Big Endian Machine.
*/
static short getShortBE (char *data)
{
return (short) ((data[0] << 8) | data[1]);
}

I can understand why this function swaps bytes on a LE machine, but
why doesn't it alter 'data' on a BE machine? I've tried to understand
it with diagrams and everything, but my brain went just crazy! Can
anyone give me a simple explanation please? :) I'm really curious...
...


I think it is rather obvious. Assuming that 'data' passed to this
function actually points to a two-byte integral value (say, 'short' in
your implementation, and CHAR_BITS is 8), on a LE machine 'data[0]' is a
low-order byte of that value and 'data[1]' is a high-order byte. Doing

(data[0] << 8) | data[1]

will indeed swap these bytes, i.e. move the former low-order byte into
the high-order position and vice versa.

On a BE machine 'data[0]' is a high-order byte and 'data[1]' is a
low-order byte of a two-byte integral value. Doing

(data[0] << 8) | data[1]

will simply re-construct the original value, i.e. high-order byte is
moved to high-order position and low-order byte is placed in low-order
position. The value remains unchanged.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #11
RoSsIaCrIiLoIA wrote:
...
it converts data stored
in Big Endian (BE) format into host native format (LE on LE machines,
BE on BE machines):


it is wrong because if a char "x" is 8 bit then x<<8 == 0
...


No. In C language operands of << operators are first subjected to
integer promotions. In this case a value of type 'char' will be promoted
to a value of type 'int'. The << operator will be applied to an 'int'
operand, not to a 'char' operand. That's why what you are saying is
incorrect.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #12
On Mon, 13 Sep 2004 15:29:05 -0700, Andrey Tarasevich
<an************ **@hotmail.com> wrote:
RoSsIaCrIiLo IA wrote:
...
it converts data stored
in Big Endian (BE) format into host native format (LE on LE machines,
BE on BE machines):


it is wrong because if a char "x" is 8 bit then x<<8 == 0
...


No. In C language operands of << operators are first subjected to
integer promotions. In this case a value of type 'char' will be promoted
to a value of type 'int'. The << operator will be applied to an 'int'
operand, not to a 'char' operand. That's why what you are saying is
incorrect.


Ok
unsigned short getShortBE (unsigned char* data)
{return (data[0] << (unsigned short) 8) | data[1];}
Nov 14 '05 #13

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

Similar topics

7
4866
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As InternetExplorer But then I cant see when a user exit my objIExplorer and than an error will show up when I try to open a link in the IE window that does not exist... What can I do about this and way does it not work in win 98?
4
1964
by: pellepluttrick | last post by:
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()
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
4090
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.
35
5488
by: Sunil | last post by:
Hi all, I am using gcc compiler in linux.I compiled a small program int main() { printf("char : %d\n",sizeof(char)); printf("unsigned char : %d\n",sizeof(unsigned char)); printf("short : %d\n",sizeof(short)); printf("unsigned short : %d\n",sizeof(unsigned short)); printf("int : %d\n",sizeof(int));
1
3159
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...
2
2358
by: dougloj | last post by:
Hi. I have an ASP.NET application written in C#. To log in, a user must provide their email address and password. I already give the user a "Remember my Email Address" check box. If they check it when logging in, I store the email address in a cookie and automatically display the address when they login again. I now want to give the user a "Remember my Password" checkbox. If they check this new checkbox, I'm planning on encrypting...
2
5018
by: StanB | last post by:
I came across this weird problem: 1. Session state stops working after the app is deployed to another server because IE does not accept cookies. 2. It works if cookieless="true" in the web.config 3. Yes, I tried IE - Tools - Privacy - Accept All Cookies and also Override automatic cookie handling, Always allow session cookes
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
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
10383
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
10120
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
9200
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
7661
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
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...
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.