473,406 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Is this the correct?!

Hi all,
Is this the corrrect method to determine if the procesor is little
endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;

Nov 15 '05 #1
22 1453
Me
va******@rediffmail.com wrote:
Is this the corrrect method to determine if the procesor is little
endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;


I'm assuming you've got a

int i = 1;

above, and no, there is *no* way to determine the bit order of a type
in C. Notice, I said *bit* order, not *byte* order. A type may have any
bit ordering it chooses and its bit order in relation to another type
may not match up in any meaningful way. This would be a pretty stupid,
but perfectly legal implementation. I can think of a tou of ways how
this test can pass or fail and it relies on behavior that may or may
not give the same result on the next run of the program.

IMHO, it's best to just think of C as having signed and unsigned
integer types with guaranteed minimum limits and being careful not to
overflow/underflow the signed integer types instead of trying to do
anything tricky.

Nov 15 '05 #2
va******@rediffmail.com wrote:
Hi all,
Is this the corrrect method to determine if the procesor is little
endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;


Hmmm, there must be something missing here (or I am missing something ;) )

What you could do, is write a long (such as 0x12345678) to memory, and read
it in byte by byte (I can think of at least three mappings, but in your case
just reading the first byte will probably suffice).

long l = 0x12345678;

if ( *(char*)&l == 0x12 )
/* big endian */
else
/* little endian */

Good luck,

--
Martijn
http://www.sereneconcepts.nl
Nov 15 '05 #3
va******@rediffmail.com wrote:
Hi all,
Is this the corrrect method to determine if the procesor is
little endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;


Please read the FAQ before posting to clc...

http://www.eskimo.com/~scs/C-faq/q20.9.html

--
Peter

Nov 15 '05 #4
This will behave correctly.

#include <stdio.h>

int main(int argc,char *argv[])

{

union

{

short s;

char c[sizeof(short)];

}myUn;

myUn.s = 0x0102;

if(sizeof(short) == 2)

{

if(myUn.c[0] == 1 && myUn.c[1] == 2)

printf("\nBig Endian\n");

else if(myUn.c[0] == 2 && myUn.c[1] == 1)

printf("\nSmall Endian\n");

else

printf("\nNo Match\n");

}

else

printf("\nTry a data type whose size is 2\n");

return 0;

}

Nov 15 '05 #5
In article <11**********************@g49g2000cwa.googlegroups .com>
<va******@rediffmail.com> wrote:
Is this the corrrect method to determine if the procesor is little
endian or Big endian.


[method snipped; but see the FAQ]

What will you do on a PDP-11, which is both little and big endian
simultaneously? 32-bit values stored in a "long" are made of
two 16-bit values stored in big-endian order, where those two
16-bit values are themselves made of two 8-bit values stored in
little-endian order.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '05 #6
Peter Nilsson wrote:
va******@rediffmail.com wrote:
Hi all,
Is this the corrrect method to determine if the procesor is
little endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;


Please read the FAQ before posting to clc...

http://www.eskimo.com/~scs/C-faq/q20.9.html


Hmm, in light of the FAQ does that mean that "Me"'s explanation of the
bit ordering possibly being different false? In other words, will the
check for endianness as described in the faq work on any
implementation? What happens if sizeof char == sizeof int ? If they
were both 2 bytes wouldn't that test fail?

Nov 15 '05 #7
In article <11**********************@g49g2000cwa.googlegroups .com>,
"joshc" <jo********@gmail.com> wrote:
Peter Nilsson wrote:
va******@rediffmail.com wrote:
Hi all,
Is this the corrrect method to determine if the procesor is
little endian or Big endian.
if((*(char*)&i)==1)
lil_end = TRUE;
else
lil_end = FALSE;


Please read the FAQ before posting to clc...

http://www.eskimo.com/~scs/C-faq/q20.9.html


Hmm, in light of the FAQ does that mean that "Me"'s explanation of the
bit ordering possibly being different false? In other words, will the
check for endianness as described in the faq work on any
implementation? What happens if sizeof char == sizeof int ? If they
were both 2 bytes wouldn't that test fail?


If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.

The test could easily fail on implemenations that have padding bits. On
the other hand, there could be implementations where "little endian" and
"big endian" doesn't even make sense.
Nov 15 '05 #8
In article <da*********@news4.newsguy.com>,
Chris Torek <no****@torek.net> wrote:
In article <11**********************@g49g2000cwa.googlegroups .com>
<va******@rediffmail.com> wrote:
Is this the corrrect method to determine if the procesor is little
endian or Big endian.


[method snipped; but see the FAQ]

What will you do on a PDP-11, which is both little and big endian
simultaneously? 32-bit values stored in a "long" are made of
two 16-bit values stored in big-endian order, where those two
16-bit values are themselves made of two 8-bit values stored in
little-endian order.


Can we please make it part of the religion of this NG that when people post
questions like this, they must also provide why they want to know?

I.e., we seem to do a pretty good job of stomping on them for all the OT
stuff, can't we also stomp on them for posting silly things w/o any
rationale given?

Nov 15 '05 #9
>
If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.


I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2? Care to
explain why you think otherwise?

As far as me personally when I read through this thread I wondered if
there indeed was a way of determining endianness in a portable way. I
certainly could see the benefit of determining endianness in an
embedded context.

Nov 15 '05 #10
On 9 Jul 2005 15:14:43 -0700, in comp.lang.c , "joshc"
<jo********@gmail.com> wrote:

If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.


I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2?


AFAIK an implementation with sizeof char == sizeof int would be legal,
but would have some big problems. Consider the case of getchar().
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #11
In article <11**********************@f14g2000cwb.googlegroups .com>,
"joshc" <jo********@gmail.com> wrote:

If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.

I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2? Care to
explain why you think otherwise?


No. "char" is the unit in which sizes are measured. sizeof xxx == 2
means that xxx is as large as two chars. A char is always exactly as
large as a char, therefore sizeof (char) == 1.
As far as me personally when I read through this thread I wondered if
there indeed was a way of determining endianness in a portable way. I
certainly could see the benefit of determining endianness in an
embedded context.


Not portable. There may be non-portable methods that work on all
implementations that you are interested in. The usual solution is to use
some macro that is defined differently from implementation to
implementation.
Nov 15 '05 #12
In article <11**********************@f14g2000cwb.googlegroups .com> "joshc" <jo********@gmail.com> writes:
....
I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2? Care to
explain why you think otherwise?


sizeof char == sizeof int is certainly possible. sizeof char == 2 is
certainly *not* possible. sizeof char == 1 by definition.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 15 '05 #13
In article <11**********************@f14g2000cwb.googlegroups .com>,
joshc <jo********@gmail.com> wrote:

If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.

I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2? Care to
explain why you think otherwise?


I'm sure that that is allowed. I think there was discussion pretty
recently about some implementation where everything was 32 bits (char, int,
long).
As far as me personally when I read through this thread I wondered if
there indeed was a way of determining endianness in a portable way. I
certainly could see the benefit of determining endianness in an
embedded context.


Really? How/why?

Nov 15 '05 #14
>>> If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.


I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2? Care to
explain why you think otherwise?


I'm sure that that is allowed. I think there was discussion pretty
recently about some implementation where everything was 32 bits (char, int,
long).


In that situation:
sizeof char = 1
sizeof int = 1
sizeof long = 1

sizeof char = 2 is never allowed.

Gordon L. Burditt
Nov 15 '05 #15
> In that situation:
sizeof char = 1
sizeof int = 1
sizeof long = 1

sizeof char = 2 is never allowed.

Gordon L. Burditt


Yeah, good point. I guess what I intended to convey was the situation
where sizeof char is 16-bits or greater assuming a 2's complement
implementation, and sizeof char == sizeof int.

As far as why determining the endianness may be important, I often
write code to communicate among devices via SPI on devices where the
transmit buffer is 8 bits. Since I have to send data as a stream of
bytes, endianness becomes important. All the existing code assumes big
endian micros. We only use 2's complement implementations but I don't
see why we might not switch to a little-endian architecture.

Nov 15 '05 #16
joshc wrote:
If both were 2 bytes then I can't say whether the test would fail or
pass, but I can tell you with certainty that you wouldn't be using a C
compiler.

I don't have the standard in front of me at this moment, but couldn't a
conforming implementation have sizeof char == sizeof int == 2?


No. sizeof(char) == 1 by definition.
If you think that sizeof() returns sizes in octets, you are wrong. It
yields sizes in terms of the byte, the amount of space that a char
occupies. If your char has 16 bits, then CHAR_BIT is 16, and a byte has
16 bits. Those 16-bit bytes could be made of two octets. Or not.

Nov 15 '05 #17
joshc wrote:
.... snip ...
As far as why determining the endianness may be important, I often
write code to communicate among devices via SPI on devices where the
transmit buffer is 8 bits. Since I have to send data as a stream of
bytes, endianness becomes important. All the existing code assumes big
endian micros. We only use 2's complement implementations but I don't
see why we might not switch to a little-endian architecture.


Then you have all you need to know, i.e. the form during
transmission. All you have to do is write code that doesn't depend
on endianness. integer multiply and divide by 256 and masking to 8
bits seem appropriate. It doesn't even need to know anything about
byte size (CHAR_BIT).

When you are done you won't need any special code on any of your
machines, and you may appreciate the power of standards.

--
Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt>
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
<http://www.dinkumware.com/refxc.html> (C-library}
<http://gcc.gnu.org/onlinedocs/> (GNU docs)

Nov 15 '05 #18
In article <11**********************@g47g2000cwa.googlegroups .com>
joshc <jo********@gmail.com> wrote:
As far as why determining the endianness may be important, I often
write code to communicate among devices via SPI on devices where the
transmit buffer is 8 bits. Since I have to send data as a stream of
bytes, endianness becomes important.


In that case, do it yourself, so that you have control:

unsigned char message[SIZE];

... verify that "len" is in range, e.g., does not exceed 1023 ...
message[0] = FOO_CODE;
message[1] = (len >> 8) & 0xff; /* assumes len >= 0 */
message[2] = len & 0xff;
memcpy(&message[3], whatever, len);
send_SPI_data(..., message, len + 3);

This code works if your machine is little-endian, big-endian,
PDP-endian, or even My-Favorite-Martian-antenna-endian. It works
if your "char"s are 8 bits, or 9 bits, or 16 bits, or 32 bits
(provided send_SPI_data() can somehow manage to send the low 8 bits
of each "unsigned char" out to the appropriate device).

In short, it always works.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '05 #19
"joshc" <jo********@gmail.com> writes:
In that situation:
sizeof char = 1
sizeof int = 1
sizeof long = 1

sizeof char = 2 is never allowed.

Gordon L. Burditt


Yeah, good point. I guess what I intended to convey was the situation
where sizeof char is 16-bits or greater assuming a 2's complement
implementation, and sizeof char == sizeof int.

As far as why determining the endianness may be important, I often
write code to communicate among devices via SPI on devices where the
transmit buffer is 8 bits. Since I have to send data as a stream of
bytes, endianness becomes important. All the existing code assumes big
endian micros. We only use 2's complement implementations but I don't
see why we might not switch to a little-endian architecture.


There's a group of non-standard functions that handle conversions
between host byte order and network byte order. (Network byte order
is MSB first.) Look up htonl, htons, ntohl, and ntohs. If you need
more information than your system's documentation provides, try a
system-specific newsgroup such as comp.unix.programmer.

--
Keith Thompson (The_Other_Keith) 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.
Nov 15 '05 #20
On 9 Jul 2005 17:33:12 -0700, joshc
<jo********@gmail.com> wrote:
As far as why determining the endianness may be important, I often
write code to communicate among devices via SPI on devices where the
transmit buffer is 8 bits. Since I have to send data as a stream of
bytes, endianness becomes important. All the existing code assumes big
endian micros. We only use 2's complement implementations but I don't
see why we might not switch to a little-endian architecture.


The portable way to do it is to decide in your protocol which way round
things are going to be passed ("network byte order" as used in TCP/IP is
defined by the standards for that protocol as MSB first, for instance)
and convert the data using C arithmetic operators:

void put8bit(unsigned char v);

void put16(unsigned short v)
{
put8(v >> 8);
put8(v);
}

void put32(unsigned long v)
{
put16(v >> 16);
put16(v);
}

unsigned char get8(void);

unsigned short get16(void)
{
unsigned short v = (unsigned short)get8() << 8;
return v + get8();
}

unsigned long get32(void)
{
unsigned long v = (unsigned long)get16() << 8;
return v + get16();
}

I've used unsigned short and unsigned long because the former is
guaranteed to be at least 16 bits and the latter guaranteed to be at
least 32 bits. If you have stdint.h on your sustem you can use the
appropriate sized types.

The functions are illustrative, and I've deliberately left the 8 bit put
and get functions undefined, additional parameters can be added, there's
no error checking, etc. The point is that the routies are totally
agnostic of the underlying representations on the target machine and are
thus fully portable.

putX() and getX() can easily be defined for structures in that way.

If you want to pass signed data, you will need to build into the
protocol a portable method of doing it, since not all processors are 2-s
complement (although in practice you may be able to assume that for your
system). Something like:

void puts32(long v)
{
if (v < 0)
{
/* possibly handle LONG_MIN == 0x80000000 case */
put32(0x80000000 | -v);
}
else
put32(v);
}

long gets32(void)
{
unsigned long v = get32();
if (v & 0x80000000)
return -(long)(v & 0x7FFFFFFF);
else
return (long)v;
}

Or something like that.

In regard to your point about embedded systems in general needing to
know what endianness they are, in almost all cases[1] this can be
determined by the system builder before compilation and set a define to
flag which is being used:

#ifdef MSB_FIRST
/* do little-endian stuff */
#else
/* do big-endian stuff */
#endif

Anything like that should be restricted to a small part of the program,
so that if you need to cope with something like the PDP-11
bastard-endian (3412 or something like that) you can easily add extra
code to do it.

An alternative way of doing it is to provide macros or functions,
contitionally compiled to get the right ones, which do the conversions.
Look at the POSIX ntohl and ntohs macros, for example.

Chris C
Nov 15 '05 #21


Chris Torek wrote:
In that case, do it yourself, so that you have control:

This code works if your machine is little-endian, big-endian,
PDP-endian, or even My-Favorite-Martian-antenna-endian. It works
if your "char"s are 8 bits, or 9 bits, or 16 bits, or 32 bits
(provided send_SPI_data() can somehow manage to send the low 8 bits
of each "unsigned char" out to the appropriate device).

In short, it always works.


Cool! Thanks to Chris Torek and CBFalconer. I've only been trying to
write standard C for about 6 months so at times it becomes difficult
for me to distinguish what is portable and what isn't since I work in
the embedded realm. I'm a bit embarassed to say that I recently
graduated from one of the top 5 computer science schools but no
emphasis was really placed on the Standard. We used K&R as a reference,
but as long as it all ran on the particular implementation in the
computer labs, that's all that mattered.

Thanks again!

Nov 15 '05 #22
joshc wrote:
Chris Torek wrote:
In that case, do it yourself, so that you have control:

This code works if your machine is little-endian, big-endian,
PDP-endian, or even My-Favorite-Martian-antenna-endian. It works
if your "char"s are 8 bits, or 9 bits, or 16 bits, or 32 bits
(provided send_SPI_data() can somehow manage to send the low 8 bits
of each "unsigned char" out to the appropriate device).

In short, it always works.


Cool! Thanks to Chris Torek and CBFalconer. I've only been trying to
write standard C for about 6 months so at times it becomes difficult
for me to distinguish what is portable and what isn't since I work
in the embedded realm. I'm a bit embarassed to say that I recently
graduated from one of the top 5 computer science schools but no
emphasis was really placed on the Standard. We used K&R as a
reference, but as long as it all ran on the particular
implementation in the computer labs, that's all that mattered.


You are welcome. This is a refreshing attitude after all the types
who come back with an argument and 'it works on my machine'.

Look around on <http://www.open-std.org/jtc1/sc22/wg14/www/docs/>
for n1124 (3.5 MB) and n869 (1.1 to 1.5 MB) which are free drafts
of the upcoming C05 and past C99 standards. For n869 you can get a
text version, which is searchable with grep and similar tools. On
my site <http://cbfalconer.home.att.net/download> you can find a
slightly edited version (for searching and quoting) in n869_txt.bz2
(212 KB).

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 15 '05 #23

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

Similar topics

1
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to...
1
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to...
2
by: thisis | last post by:
Hi All, I need the PUBS.mdb for pulling images: PUBS.mdb must have the table: pub_info tbl_pub_info : has 3 fields Data_Type : ok Data_Type : ok
3
lee123
by: lee123 | last post by:
I have a problem getting the correct to count +1 every time I get an answer right and the incorrect is the same. I have two lbl's named number1 and number2 which produces a Rnd# in each lbl. ...
10
by: onetruelove | last post by:
I want to creat a post like this blog: http://onlinetoefltest.blogspot.com/2007/08/level-c-lesson-1.html When you chose all the answers and click show answer a msg box will appear and tells how...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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,...

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.