Upending a Network value

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
dlh
Posts: 395
Joined: 15 December 2006, 12:12 PM
Location: ~Cincinnati

Upending a Network value

Post by dlh »

I need to convert a big-endian network value to little-endian Unsigned Long. Does anyone have code for this?[/i]
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: Upending a Network value

Post by dkinzer »

dlh wrote:Does anyone have code for this?
The code below can be used for swapping the byte order when changing from network order to host order and vice versa.

Code: Select all

'
'' revByteOrder
'
' This function reverses the order of the bytes of a 32-bit value.
'
Function revByteOrder(ByVal val as UnsignedLong) as UnsignedLong
  ' define some based arrays for accessing the constituent bytes
  Dim valBytesIn() as Byte Based val.DataAddress
  Dim valBytesOut() as Byte Based revByteOrder.DataAddress

  ' reverse the byte order
  revByteOrder = CULng(valBytesIn(4))
  valBytesOut(2) = valBytesIn(3)
  valBytesOut(3) = valBytesIn(2)
  valBytesOut(4) = valBytesIn(1)
End Function
- Don Kinzer
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post by dkinzer »

Here is a variation of the code above that is more uniform and demonstrates how to use a pragma to temporarily suppress a compiler warning. Without the pragma, the compiler will complain that not all paths through the function set the return value because the return value is not set directly. The warning includes the message number (2 in this case) and that is the number used for turning off the warning. The push and pop aspects of the pragma allow you to temporarily change the warning settings and then return to whatever was previously in effect.

Code: Select all

#pragma warning(push; 2:Off)  ' turn off warning: return value not set
Function revByteOrder(ByVal val as UnsignedLong) as UnsignedLong
  ' define some based arrays for accessing the constituent bytes
  Dim valBytesIn() as Byte Based val.DataAddress
  Dim valBytesOut() as Byte Based revByteOrder.DataAddress

  ' reverse the byte order
  valBytesOut(1) = valBytesIn(4)
  valBytesOut(2) = valBytesIn(3)
  valBytesOut(3) = valBytesIn(2)
  valBytesOut(4) = valBytesIn(1)
End Function
#pragma warning(pop)
- Don Kinzer
dlh
Posts: 395
Joined: 15 December 2006, 12:12 PM
Location: ~Cincinnati

Post by dlh »

Thanks, Don.
Post Reply