c#


What is the C# equivalent of the PHP Pack() function?


I have a line of PHP code that does the following:
$xml = "<xml><request>...[snipped for brevity]...</request></xml>";
$request = pack('N', (strlen($xml)+4)).$xml;
What this appears to do is prepend a binary string of the length of $xml (plus 4) to the value of $xml.
How do I do the equivalent of this in C#?
It looks like your request requires a length prefixed string made up of single byte characters, so it's gonna need a bit more work in C# which uses Unicode characters. I'm going to assume you want your string of XML encoded with UTF-8. We also won't be able to use a string to hold the request when its been put together, instead we'll use a byte array.
using System;
using System.IO;
using System.Text;
class Program
{
static void
Main(string[] args)
{
string xml = "<xml><request>...[snipped for brevity]...</request></xml>";
using ( MemoryStream stream = new MemoryStream() )
{
using ( BinaryWriter writer = new BinaryWriter(stream) )
{
byte [] encodedXml = Encoding.UTF8.GetBytes(xml);
writer.Write(ToBigEndian(encodedXml.Length + 4));
writer.Write(encodedXml);
}
byte [] request = stream.ToArray();
// now use request however you like
}
}
static byte []
ToBigEndian(int value)
{
byte [] retval = BitConverter.GetBytes(value);
if ( BitConverter.IsLittleEndian )
{
Array.Reverse(retval);
}
return retval;
}
}
The other thing to notice here is that the php pack() function with the 'N' parameter forces big-endian on your leading 4 bytes. I therefore wrote the ToBigEndian() method to handle conversion into big-endian on any platform.
System.IO.BinaryWriter would appear to be a closer match.
I'm not a PHP guru (haven't used it in years), but the following is probably pretty close in functionality:
using System.IO;
using System.Text;
string xml = "the original data to pack";
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
byte[] data = Encodings.ASCII.GetBytes(xml);
bw.Write((Int32)data.Length + 4); // Size of ASCII string + length (4 byte int)
bw.Write(data);
}
request = ms.ToArray();
}

Related Links

How to passing value to textbox in second form when object has been lunched
Make my datepicker required and remove it after selecting a date in c#
Microsoft Graph. DriveItem Id format?
DateTime parsing - unexpected result
Measuring mb sent per second with C# sockets? (Multithread)
C# inheritance multiple for different children
IList to JSON fails
Convert to Nested JSON C#
Sending List<Object> WCF POST
Export to excel is exporting check box to excel instead of string
Loop iteration of an array string
Impersonate a user using the Session ID
Is it safe to store and update list in asp.net session via static methods?
Change of the edited cell in a datagridview cell
Trying a REST POST call in C# - using Postman code
List object initialization [duplicate]

Categories

HOME
joomla
azure-active-directory
virtual-machine
display
phantomjs
c++builder
spotfire
x509certificate
salesforce-lightning
app-store
opc-ua
cdn
unreal-engine4
mongodb-replica-set
opengrok
geography
computation-theory
monad-transformers
resx
jms-topic
sphinx4
arp
lines
wercker
luhn
favorites
instances
aspose.pdf
definition
pexpect
encoder
emacs24
px4
fluent-nhibernate-mapping
gige-sdk
r-commander
petapoco
printer-control-language
scanf
qt3d
qudpsocket
gevent
distcc
class-design
gdi
boost-bind
laterjs
jde
archiva
ideavim
trendline
jsondoc
overlapping
tvp
android-togglebutton
web-standards
teamwork
jeet-grid
screen-lock
autopep8
dockerpy
os.walk
sat4j
amzi-prolog
atg-dynamo
nspopupbutton
pyalgotrade
banana-pi
xps
email-headers
fastcgi-mono-server
pthreads-win32
php-amqplib
surfaceview
friendly-url
select2-rails
magicsuggest
pageload
django-tinymce
nsregularexpression
beep
winrt-async
flatten
eeprom
stl-algorithm
rjs
execjs
xpolog
database-agnostic
for-xml
dynamic-scope
file-storage
qlibrary
moores-law

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App