473,655 Members | 3,072 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

littleEndian/bigEndian

Hi,

as someone pulling to C# over from C++ I stumbled over something today for
which I was not able to find an answer:

HOW do I convert a byte block with a given endianess to an int32 and vice
versa?

In C++ I have this:

#pragma intrinsic(_byte swap_ushort)
#pragma intrinsic(_byte swap_ulong)

*myword = _byteswap_ulong (mybigendianwor d);

which results in a wonderful single assembler instruction.

The only documentation I found about endianess is on handling UTF8/16
strings, but not with binary stuff.

Can someone give me a hint how I perform such things FAST and not via my own
clumsy version?

thanks
doc

Jun 29 '06 #1
19 8018
docschnipp wrote:
as someone pulling to C# over from C++ I stumbled over something today for
which I was not able to find an answer:

HOW do I convert a byte block with a given endianess to an int32 and vice
versa?


Have a look at http://www.pobox.com/~skeet/csharp/miscutil
In particular, the EndianBinaryRea der/Writer and EndianBitConver ter.

Jon

Jun 29 '06 #2
"Jon Skeet [C# MVP]" wrote:
docschnipp wrote:
as someone pulling to C# over from C++ I stumbled over something today for
which I was not able to find an answer:

HOW do I convert a byte block with a given endianess to an int32 and vice
versa?


Have a look at http://www.pobox.com/~skeet/csharp/miscutil
In particular, the EndianBinaryRea der/Writer and EndianBitConver ter.

"Every so often, someone on the newsgroup asks about something which doesn't
exist in the framework, but which I think should. Sometimes, I'll write some
code for them to plug the gap. "

Well, fits perfect I guess :)

I'll take a look into it, thanks.

doc

Jun 29 '06 #3
Hello docschnipp,

Here's what I currently use (in VB):

Public Function ReadBigEndianIn t32() As Int32

Dim tReturn As Int32 = 0
Dim tBuffer(3) As Byte

oStream.Read(tB uffer, 0, tBuffer.Length)

Array.Reverse(t Buffer)
tReturn = BitConverter.To Int32(tBuffer, 0)

Return tReturn

End Function

And the inverse of course for Writing..

-Boo
Hi,

as someone pulling to C# over from C++ I stumbled over something today
for which I was not able to find an answer:

HOW do I convert a byte block with a given endianess to an int32 and
vice versa?

In C++ I have this:

#pragma intrinsic(_byte swap_ushort)
#pragma intrinsic(_byte swap_ulong)
*myword = _byteswap_ulong (mybigendianwor d);

which results in a wonderful single assembler instruction.

The only documentation I found about endianess is on handling UTF8/16
strings, but not with binary stuff.

Can someone give me a hint how I perform such things FAST and not via
my own clumsy version?

thanks
doc

Jun 29 '06 #4
GhostInAK <gh*******@gmai l.com> wrote:
Here's what I currently use (in VB):

Public Function ReadBigEndianIn t32() As Int32

Dim tReturn As Int32 = 0
Dim tBuffer(3) As Byte

oStream.Read(tB uffer, 0, tBuffer.Length)

Array.Reverse(t Buffer)
tReturn = BitConverter.To Int32(tBuffer, 0)

Return tReturn

End Function


That's not guaranteed to work - calling Read on a stream isn't
guaranteed to read all the bytes you ask for. It's likely to, but it's
not guaranteed.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 29 '06 #5
IPAddress.Netwo rkToHostOrder
IPAddress.HostT oNetworkOrder

(not sure why these are in the IPAddress class but they're static anyway)

/claes

"docschnipp " <do********@new sgroup.nospam> wrote in message
news:BC******** *************** ***********@mic rosoft.com...
Hi,

as someone pulling to C# over from C++ I stumbled over something today for
which I was not able to find an answer:

HOW do I convert a byte block with a given endianess to an int32 and vice
versa?

In C++ I have this:

#pragma intrinsic(_byte swap_ushort)
#pragma intrinsic(_byte swap_ulong)

*myword = _byteswap_ulong (mybigendianwor d);

which results in a wonderful single assembler instruction.

The only documentation I found about endianess is on handling UTF8/16
strings, but not with binary stuff.

Can someone give me a hint how I perform such things FAST and not via my
own
clumsy version?

thanks
doc

Jun 29 '06 #6
Hello Jon Skeet [C# MVP],

Jon,

Thanks for the comment. I became aware of that fact the other day and just
hadn't got around to updating the routine at the time of the post.

Thanks,
-Boo
GhostInAK <gh*******@gmai l.com> wrote:
Here's what I currently use (in VB):

Public Function ReadBigEndianIn t32() As Int32

Dim tReturn As Int32 = 0
Dim tBuffer(3) As Byte
oStream.Read(tB uffer, 0, tBuffer.Length)

Array.Reverse(t Buffer)
tReturn = BitConverter.To Int32(tBuffer, 0)
Return tReturn

End Function

That's not guaranteed to work - calling Read on a stream isn't
guaranteed to read all the bytes you ask for. It's likely to, but it's
not guaranteed.

Jun 29 '06 #7
"Claes Bergefall" wrote:
IPAddress.Netwo rkToHostOrder
IPAddress.HostT oNetworkOrder

(not sure why these are in the IPAddress class but they're static anyway)

/claes


Usually because the libs connected to sockets, tcp/ip etc. are early cross
platform libs and need all the translation of network to local endianess.

I now decided to use this variant until I find something better:

----------
UInt32 myBigEndian = 0xdeadbeef;
UInt32 mLittleEndian = ( (myBigEndian& 0xFF000000) >> 24) | ((myBigEndian&
0x00FF0000) >>8) | (( myBigEndian& 0x0000FF00) <<8 ) | ((myBigEndian&
0x000000FF) << 24);
----------

The big advantage is: it works for all scales of integers and is not too
clumsy. Unfortunately I found no source for something that allows the native
compiler to take use of the bswap mnemonic. I would really appreciate a way
to make this very fast. bswap takes 2 ( 1 cycle plus prefix ) cycles only,
the code above ~34 cycles.

I have to read a _lot_ of data, several dozends of megabytes so
investigation on this topic is a worthwhile goal for me.
thanks for input,

doc

Jul 1 '06 #8
Hi Guys,

I've made some tests, the Reverse() method seems to be the slowest of all.

The code is found below, results were:

Time 1: 3765 ( the .Reverse/BitConverter method )
Time 2: 1322 ( the manual reindexing/BitConverter method )
Time 3: 1071 ( the Bitconverter/reshift method )
(if UInt is not needed, only Int:)
Time 4: 191 ( the shift the bytes directly/OR method )
So I think I will stick to method 3 and 4. Does anyone knows how I can cast
a byte to uint? :)

Thanks for all your input.

UInt32 mLittleEndian;
int loopcount = 20000000;

s1 = Environment.Tic kCount;
Array.Copy(myOr g,0,myArr,0,4);
for (i = 0; i < loopcount; i++)
{
if ( BitConverter.Is LittleEndian )
{
Array.Reverse(m yNew,0,4);
}
mLittleEndian = BitConverter.To UInt32(myNew,0) ;
}
s2 = Environment.Tic kCount;
Array.Copy(myOr g,0,myArr,0,4);
for ( i = 0; i< loopcount ; i++)
{
if ( BitConverter.Is LittleEndian )
{

myNew[3] = myArr[0];
myNew[2] = myArr[1];
myNew[1] = myArr[2];
myNew[0] = myArr[3];
mLittleEndian = BitConverter.To UInt32(myNew,0) ;
}
}
s3 = Environment.Tic kCount;

// UInt32 mLittleEndian;
for ( i = 0; i< loopcount ; i++)
{
// myBigEndian = BitConverter.To UInt32(myNew,0) ;
myBigEndian = BitConverter.To UInt32(myOrg,0) ;
if ( BitConverter.Is LittleEndian)
{
mLittleEndian = ( (myBigEndian & 0xFF000000) >24) |
((myBigEndian & 0x00FF0000) >>8) | (( myBigEndian &
0x0000FF00) <<8 ) | ((myBigEndian & 0x000000FF) << 24);
}
}
s4 = Environment.Tic kCount;
Int32 mSLittleEndian;
for ( i = 0; i< loopcount ; i++)
{
if ( BitConverter.Is LittleEndian)
{
mSLittleEndian = myArr[0] | (myArr[1] << 8) | (myArr[2] << 16) | (myArr[3]
<< 24);
}
}
s5 = Environment.Tic kCount;
s1 = s2-s1;
s2 = s3-s2;
s3 = s4-s3;
s4 = s5-s4;
Console.WriteLi ne("Time 1: {0} Time 2: {1} Time 3: {2} Time 4:
{3}",s1.ToStrin g(),s2.ToString (),s3.ToString( ),s4.ToString() );

Jul 2 '06 #9
Hi Docschnipp,

Thanks for your feedback!

Yes, I see your concern, BSWAP instruction should be faster than manually
change the byte order. However, based on my experience, C# does not
contains the code statement to generate this specific instruction.(I think
JIT compiler takes control of the instructions generated)

To workaround this issue, I think you may use C/C++ to write a dll which
internally uses inline ASM to call BSWAP instruction. Then in C# code, you
may p/invoke the exported function of the C/C++ dll to call BSWAP
indirectly. You can also declare the C/C++ function as naked to eliminate
the function prolog and epilog.

Hope this helps!

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Jul 3 '06 #10

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

Similar topics

3
2107
by: TF | last post by:
Hi, I've a byte array with 4 elements in BigEndian format i.e. {0, 0, 0, 12} and i want to convert it to 4-byte integer (Int32). I am trying Encoding.BigEndianUnicode property but it has no effect on the result. It always gives me number '201326592' instead of '12'. Any help?? Here is the code:
55
3792
by: Sharon | last post by:
hi all, I generate binary text file (in Windows using Dev-C++) Is the generated binary file using BigEndian? Are there any method to generate binary file using LittleEndian? Because I want the generated binary file to be used in Palm, is it necessary to do so ? thanks!
14
19034
by: Laszlo Szijarto | last post by:
Can BinaryReader be forced to read a stream, say a TCP/IP stream or memory stream or even file stream in big endian order or do I have to write something custom to reverse the byte order? So, for example, I'd like a Windows client PC (native little endian) to be able to read a network stream coming in as big endian. I want to be able to read a short for example without worrying about flipping the bytes. Thank you, Laszlo
0
8380
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
8296
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
8816
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...
1
8497
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
7310
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
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
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...
2
1928
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1598
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.