Add range dynamically to list
I have a List<byte>
that stores the value of a variable byte
by byte
. I am trying to build up this variable by respect to its original data type.
Example of the result:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
//After the conversion of UInt32:
varReady = 0x78563412;
Here is a snippet of my class that returns the value of the variable.
public static object GetTypedString(List<byte> varBytes, string varType)
{
object varReady;
switch (varType)
{
case "uint16":
UInt16 varReady = BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
break;
case "uint32":
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
//repeat case for each data type
}
return varReady ;
}
The problem comes up if my variable is only 2 bytes long and if I want to show that variable as UInt32
. The BitConverter.ToUInt32
will throw this exception:
Destination array is not long enough to copy all the items in the collection.
Because the varBytes
list only has 2 bytes but BitConverter.ToUInt32
is trying to read 4 bytes. My solution was to add dummy bytes to the end of the list in this case:
.
.
.
case "uint32":
int difference = sizeof(UInt32) - varSize; //we know the variable size already
if(difference > 0)
{
varToDisp.value.AddRange(new byte[difference]);
}
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
.
.
.
This works but didn't seem a good way to me since it will edit the original List
and consumes some time. Is there any easier way to achieve this?
c# list types type-conversion
|
show 3 more comments
I have a List<byte>
that stores the value of a variable byte
by byte
. I am trying to build up this variable by respect to its original data type.
Example of the result:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
//After the conversion of UInt32:
varReady = 0x78563412;
Here is a snippet of my class that returns the value of the variable.
public static object GetTypedString(List<byte> varBytes, string varType)
{
object varReady;
switch (varType)
{
case "uint16":
UInt16 varReady = BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
break;
case "uint32":
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
//repeat case for each data type
}
return varReady ;
}
The problem comes up if my variable is only 2 bytes long and if I want to show that variable as UInt32
. The BitConverter.ToUInt32
will throw this exception:
Destination array is not long enough to copy all the items in the collection.
Because the varBytes
list only has 2 bytes but BitConverter.ToUInt32
is trying to read 4 bytes. My solution was to add dummy bytes to the end of the list in this case:
.
.
.
case "uint32":
int difference = sizeof(UInt32) - varSize; //we know the variable size already
if(difference > 0)
{
varToDisp.value.AddRange(new byte[difference]);
}
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
.
.
.
This works but didn't seem a good way to me since it will edit the original List
and consumes some time. Is there any easier way to achieve this?
c# list types type-conversion
YourGetTypedString
method will not compile.
– SeM
Nov 20 '18 at 8:24
Sorry, I had simplified the code to paste here. I addedreturn
value and it should be okay now.
– abdullah cinar
Nov 20 '18 at 8:27
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
Does the byte array originate from anUInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?
– CodeCaster
Nov 20 '18 at 8:32
|
show 3 more comments
I have a List<byte>
that stores the value of a variable byte
by byte
. I am trying to build up this variable by respect to its original data type.
Example of the result:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
//After the conversion of UInt32:
varReady = 0x78563412;
Here is a snippet of my class that returns the value of the variable.
public static object GetTypedString(List<byte> varBytes, string varType)
{
object varReady;
switch (varType)
{
case "uint16":
UInt16 varReady = BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
break;
case "uint32":
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
//repeat case for each data type
}
return varReady ;
}
The problem comes up if my variable is only 2 bytes long and if I want to show that variable as UInt32
. The BitConverter.ToUInt32
will throw this exception:
Destination array is not long enough to copy all the items in the collection.
Because the varBytes
list only has 2 bytes but BitConverter.ToUInt32
is trying to read 4 bytes. My solution was to add dummy bytes to the end of the list in this case:
.
.
.
case "uint32":
int difference = sizeof(UInt32) - varSize; //we know the variable size already
if(difference > 0)
{
varToDisp.value.AddRange(new byte[difference]);
}
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
.
.
.
This works but didn't seem a good way to me since it will edit the original List
and consumes some time. Is there any easier way to achieve this?
c# list types type-conversion
I have a List<byte>
that stores the value of a variable byte
by byte
. I am trying to build up this variable by respect to its original data type.
Example of the result:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
//After the conversion of UInt32:
varReady = 0x78563412;
Here is a snippet of my class that returns the value of the variable.
public static object GetTypedString(List<byte> varBytes, string varType)
{
object varReady;
switch (varType)
{
case "uint16":
UInt16 varReady = BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
break;
case "uint32":
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
//repeat case for each data type
}
return varReady ;
}
The problem comes up if my variable is only 2 bytes long and if I want to show that variable as UInt32
. The BitConverter.ToUInt32
will throw this exception:
Destination array is not long enough to copy all the items in the collection.
Because the varBytes
list only has 2 bytes but BitConverter.ToUInt32
is trying to read 4 bytes. My solution was to add dummy bytes to the end of the list in this case:
.
.
.
case "uint32":
int difference = sizeof(UInt32) - varSize; //we know the variable size already
if(difference > 0)
{
varToDisp.value.AddRange(new byte[difference]);
}
UInt32 varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
break;
.
.
.
This works but didn't seem a good way to me since it will edit the original List
and consumes some time. Is there any easier way to achieve this?
c# list types type-conversion
c# list types type-conversion
edited Nov 20 '18 at 9:17
abdullah cinar
asked Nov 20 '18 at 8:17
abdullah cinarabdullah cinar
178314
178314
YourGetTypedString
method will not compile.
– SeM
Nov 20 '18 at 8:24
Sorry, I had simplified the code to paste here. I addedreturn
value and it should be okay now.
– abdullah cinar
Nov 20 '18 at 8:27
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
Does the byte array originate from anUInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?
– CodeCaster
Nov 20 '18 at 8:32
|
show 3 more comments
YourGetTypedString
method will not compile.
– SeM
Nov 20 '18 at 8:24
Sorry, I had simplified the code to paste here. I addedreturn
value and it should be okay now.
– abdullah cinar
Nov 20 '18 at 8:27
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
Does the byte array originate from anUInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?
– CodeCaster
Nov 20 '18 at 8:32
Your
GetTypedString
method will not compile.– SeM
Nov 20 '18 at 8:24
Your
GetTypedString
method will not compile.– SeM
Nov 20 '18 at 8:24
Sorry, I had simplified the code to paste here. I added
return
value and it should be okay now.– abdullah cinar
Nov 20 '18 at 8:27
Sorry, I had simplified the code to paste here. I added
return
value and it should be okay now.– abdullah cinar
Nov 20 '18 at 8:27
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
Does the byte array originate from an
UInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?– CodeCaster
Nov 20 '18 at 8:32
Does the byte array originate from an
UInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?– CodeCaster
Nov 20 '18 at 8:32
|
show 3 more comments
3 Answers
3
active
oldest
votes
You can create the array (not list) with required Length
with a help of Linq Concat
; I suggest routine redesign as well.
Code:
// Let's implement a generic method: we want, say, uint not object from given list
public static T GetTypedString<T>(List<byte> varBytes) where T: struct {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
// if data is too short we should pad it; either from left or from right:
// {0, ..., 0} + data or data + {0, ..., 0}
// to choose the way, let's have a look at endiness
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
// A bit of reflection: let's find out suitable Converter method
var mi = typeof(BitConverter).GetMethod($"To{typeof(T).Name}");
if (null == mi)
throw new InvalidOperationException($"Type {typeof(T).Name} can't be converted");
else
return (T)(mi.Invoke(null, new object { data, 0 })); // or data.Length - size
}
Then you can use it as follow:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
int result1 = GetTypedString<int>(varBytes);
long result2 = GetTypedString<long>(varBytes);
Console.WriteLine(result1.ToString("x"));
Console.WriteLine(result2.ToString("x"));
// How fast it is (Linq and Reflection?)
var sw = new System.Diagnostics.Stopwatch();
int n = 10000000;
sw.Start();
for (int i = 0; i < n; ++i) {
// The worst case:
// 1. We should expand the array
// 2. The output is the longest one
long result = GetTypedString<long>(varBytes);
//Trick: Do not let the compiler optimize the loop
if (result < 0)
break;
}
sw.Stop();
Console.WriteLine($"Microseconds per operation: {(sw.Elapsed.TotalSeconds/n*1000000)}");
Outcome:
78563412
78563412
Microseconds per operation: 0.84716933
Edit: If you insist on type name (string varType
) instead of generic parameter <T>
first of all let's extract a model (type name - type correspondense):
private static Dictionary<string, Type> s_Types =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) {
{ "uint16", typeof(UInt16)},
{ "ushort", typeof(UInt16)}, // <- you can add synonyms if you want
{ "int", typeof(Int32)},
{ "int32", typeof(Int32)},
{ "long", typeof(Int64)},
{ "int64", typeof(Int64)},
//TODO: add all the other names and correspondent types
};
Then you can implement it as
public static object GetTypedString(List<byte> varBytes, string varType) {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
else if (null == varType)
throw new ArgumentNullException(nameof(varType));
Type type = null;
if (!s_Types.TryGetValue(varType, out type))
throw new ArgumentException(
$"Type name {varType} is not a valid type name.",
nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
var mi = typeof(BitConverter).GetMethod($"To{type.Name}");
if (null == mi)
throw new InvalidOperationException(
$"Type {type.Name} (name: {varType}) can't be converted");
else
return mi.Invoke(null, new object { data, 0 }); // data.Length - size
}
Demo:
string result1 = (GetTypedString(varBytes, "Int64") as IFormattable).ToString("x8", null);
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than theswitch-case
method?
– abdullah cinar
Nov 20 '18 at 9:04
1
@abdullah cinar: it took about400 nanoseconds
per call (in case ofInt32
) and800 nanoseconds
in case of (Int64
) at my workstation (less than1 microsecond
in any case).
– Dmitry Bychenko
Nov 20 '18 at 9:29
1
@abdullah cinar: you can obtainType
from itsstring
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)
– Dmitry Bychenko
Nov 20 '18 at 12:00
1
@abdullah cinar: you are quite right,char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
– Dmitry Bychenko
Nov 22 '18 at 7:31
|
show 6 more comments
Rather than using .ToArray
you could preallocate your array to the correct size and use .CopyTo
.
Example:
var byteArray = new byte[sizeof(UInt32)];
varBytes.CopyTo(byteArray);
UInt32 varReady = BitConverter.ToUInt32(byteArray, 0);
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
add a comment |
You can check for the length of the array and convert it to smaller types then cast the required one
case "uint32":
{
if (varBytes.Count == 1)
{
varReady = (UInt32)varBytes[0];
}
else if (varBytes.Count >= 2 && varBytes.Count < 4)
{
varReady = (UInt32)BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
}
else
{
varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
}
break;
}
Thanks, but if the user wants to convert them toUInt64
, I will need to add another condition too.
– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388775%2fadd-range-dynamically-to-list%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can create the array (not list) with required Length
with a help of Linq Concat
; I suggest routine redesign as well.
Code:
// Let's implement a generic method: we want, say, uint not object from given list
public static T GetTypedString<T>(List<byte> varBytes) where T: struct {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
// if data is too short we should pad it; either from left or from right:
// {0, ..., 0} + data or data + {0, ..., 0}
// to choose the way, let's have a look at endiness
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
// A bit of reflection: let's find out suitable Converter method
var mi = typeof(BitConverter).GetMethod($"To{typeof(T).Name}");
if (null == mi)
throw new InvalidOperationException($"Type {typeof(T).Name} can't be converted");
else
return (T)(mi.Invoke(null, new object { data, 0 })); // or data.Length - size
}
Then you can use it as follow:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
int result1 = GetTypedString<int>(varBytes);
long result2 = GetTypedString<long>(varBytes);
Console.WriteLine(result1.ToString("x"));
Console.WriteLine(result2.ToString("x"));
// How fast it is (Linq and Reflection?)
var sw = new System.Diagnostics.Stopwatch();
int n = 10000000;
sw.Start();
for (int i = 0; i < n; ++i) {
// The worst case:
// 1. We should expand the array
// 2. The output is the longest one
long result = GetTypedString<long>(varBytes);
//Trick: Do not let the compiler optimize the loop
if (result < 0)
break;
}
sw.Stop();
Console.WriteLine($"Microseconds per operation: {(sw.Elapsed.TotalSeconds/n*1000000)}");
Outcome:
78563412
78563412
Microseconds per operation: 0.84716933
Edit: If you insist on type name (string varType
) instead of generic parameter <T>
first of all let's extract a model (type name - type correspondense):
private static Dictionary<string, Type> s_Types =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) {
{ "uint16", typeof(UInt16)},
{ "ushort", typeof(UInt16)}, // <- you can add synonyms if you want
{ "int", typeof(Int32)},
{ "int32", typeof(Int32)},
{ "long", typeof(Int64)},
{ "int64", typeof(Int64)},
//TODO: add all the other names and correspondent types
};
Then you can implement it as
public static object GetTypedString(List<byte> varBytes, string varType) {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
else if (null == varType)
throw new ArgumentNullException(nameof(varType));
Type type = null;
if (!s_Types.TryGetValue(varType, out type))
throw new ArgumentException(
$"Type name {varType} is not a valid type name.",
nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
var mi = typeof(BitConverter).GetMethod($"To{type.Name}");
if (null == mi)
throw new InvalidOperationException(
$"Type {type.Name} (name: {varType}) can't be converted");
else
return mi.Invoke(null, new object { data, 0 }); // data.Length - size
}
Demo:
string result1 = (GetTypedString(varBytes, "Int64") as IFormattable).ToString("x8", null);
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than theswitch-case
method?
– abdullah cinar
Nov 20 '18 at 9:04
1
@abdullah cinar: it took about400 nanoseconds
per call (in case ofInt32
) and800 nanoseconds
in case of (Int64
) at my workstation (less than1 microsecond
in any case).
– Dmitry Bychenko
Nov 20 '18 at 9:29
1
@abdullah cinar: you can obtainType
from itsstring
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)
– Dmitry Bychenko
Nov 20 '18 at 12:00
1
@abdullah cinar: you are quite right,char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
– Dmitry Bychenko
Nov 22 '18 at 7:31
|
show 6 more comments
You can create the array (not list) with required Length
with a help of Linq Concat
; I suggest routine redesign as well.
Code:
// Let's implement a generic method: we want, say, uint not object from given list
public static T GetTypedString<T>(List<byte> varBytes) where T: struct {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
// if data is too short we should pad it; either from left or from right:
// {0, ..., 0} + data or data + {0, ..., 0}
// to choose the way, let's have a look at endiness
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
// A bit of reflection: let's find out suitable Converter method
var mi = typeof(BitConverter).GetMethod($"To{typeof(T).Name}");
if (null == mi)
throw new InvalidOperationException($"Type {typeof(T).Name} can't be converted");
else
return (T)(mi.Invoke(null, new object { data, 0 })); // or data.Length - size
}
Then you can use it as follow:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
int result1 = GetTypedString<int>(varBytes);
long result2 = GetTypedString<long>(varBytes);
Console.WriteLine(result1.ToString("x"));
Console.WriteLine(result2.ToString("x"));
// How fast it is (Linq and Reflection?)
var sw = new System.Diagnostics.Stopwatch();
int n = 10000000;
sw.Start();
for (int i = 0; i < n; ++i) {
// The worst case:
// 1. We should expand the array
// 2. The output is the longest one
long result = GetTypedString<long>(varBytes);
//Trick: Do not let the compiler optimize the loop
if (result < 0)
break;
}
sw.Stop();
Console.WriteLine($"Microseconds per operation: {(sw.Elapsed.TotalSeconds/n*1000000)}");
Outcome:
78563412
78563412
Microseconds per operation: 0.84716933
Edit: If you insist on type name (string varType
) instead of generic parameter <T>
first of all let's extract a model (type name - type correspondense):
private static Dictionary<string, Type> s_Types =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) {
{ "uint16", typeof(UInt16)},
{ "ushort", typeof(UInt16)}, // <- you can add synonyms if you want
{ "int", typeof(Int32)},
{ "int32", typeof(Int32)},
{ "long", typeof(Int64)},
{ "int64", typeof(Int64)},
//TODO: add all the other names and correspondent types
};
Then you can implement it as
public static object GetTypedString(List<byte> varBytes, string varType) {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
else if (null == varType)
throw new ArgumentNullException(nameof(varType));
Type type = null;
if (!s_Types.TryGetValue(varType, out type))
throw new ArgumentException(
$"Type name {varType} is not a valid type name.",
nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
var mi = typeof(BitConverter).GetMethod($"To{type.Name}");
if (null == mi)
throw new InvalidOperationException(
$"Type {type.Name} (name: {varType}) can't be converted");
else
return mi.Invoke(null, new object { data, 0 }); // data.Length - size
}
Demo:
string result1 = (GetTypedString(varBytes, "Int64") as IFormattable).ToString("x8", null);
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than theswitch-case
method?
– abdullah cinar
Nov 20 '18 at 9:04
1
@abdullah cinar: it took about400 nanoseconds
per call (in case ofInt32
) and800 nanoseconds
in case of (Int64
) at my workstation (less than1 microsecond
in any case).
– Dmitry Bychenko
Nov 20 '18 at 9:29
1
@abdullah cinar: you can obtainType
from itsstring
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)
– Dmitry Bychenko
Nov 20 '18 at 12:00
1
@abdullah cinar: you are quite right,char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
– Dmitry Bychenko
Nov 22 '18 at 7:31
|
show 6 more comments
You can create the array (not list) with required Length
with a help of Linq Concat
; I suggest routine redesign as well.
Code:
// Let's implement a generic method: we want, say, uint not object from given list
public static T GetTypedString<T>(List<byte> varBytes) where T: struct {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
// if data is too short we should pad it; either from left or from right:
// {0, ..., 0} + data or data + {0, ..., 0}
// to choose the way, let's have a look at endiness
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
// A bit of reflection: let's find out suitable Converter method
var mi = typeof(BitConverter).GetMethod($"To{typeof(T).Name}");
if (null == mi)
throw new InvalidOperationException($"Type {typeof(T).Name} can't be converted");
else
return (T)(mi.Invoke(null, new object { data, 0 })); // or data.Length - size
}
Then you can use it as follow:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
int result1 = GetTypedString<int>(varBytes);
long result2 = GetTypedString<long>(varBytes);
Console.WriteLine(result1.ToString("x"));
Console.WriteLine(result2.ToString("x"));
// How fast it is (Linq and Reflection?)
var sw = new System.Diagnostics.Stopwatch();
int n = 10000000;
sw.Start();
for (int i = 0; i < n; ++i) {
// The worst case:
// 1. We should expand the array
// 2. The output is the longest one
long result = GetTypedString<long>(varBytes);
//Trick: Do not let the compiler optimize the loop
if (result < 0)
break;
}
sw.Stop();
Console.WriteLine($"Microseconds per operation: {(sw.Elapsed.TotalSeconds/n*1000000)}");
Outcome:
78563412
78563412
Microseconds per operation: 0.84716933
Edit: If you insist on type name (string varType
) instead of generic parameter <T>
first of all let's extract a model (type name - type correspondense):
private static Dictionary<string, Type> s_Types =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) {
{ "uint16", typeof(UInt16)},
{ "ushort", typeof(UInt16)}, // <- you can add synonyms if you want
{ "int", typeof(Int32)},
{ "int32", typeof(Int32)},
{ "long", typeof(Int64)},
{ "int64", typeof(Int64)},
//TODO: add all the other names and correspondent types
};
Then you can implement it as
public static object GetTypedString(List<byte> varBytes, string varType) {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
else if (null == varType)
throw new ArgumentNullException(nameof(varType));
Type type = null;
if (!s_Types.TryGetValue(varType, out type))
throw new ArgumentException(
$"Type name {varType} is not a valid type name.",
nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
var mi = typeof(BitConverter).GetMethod($"To{type.Name}");
if (null == mi)
throw new InvalidOperationException(
$"Type {type.Name} (name: {varType}) can't be converted");
else
return mi.Invoke(null, new object { data, 0 }); // data.Length - size
}
Demo:
string result1 = (GetTypedString(varBytes, "Int64") as IFormattable).ToString("x8", null);
You can create the array (not list) with required Length
with a help of Linq Concat
; I suggest routine redesign as well.
Code:
// Let's implement a generic method: we want, say, uint not object from given list
public static T GetTypedString<T>(List<byte> varBytes) where T: struct {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
// if data is too short we should pad it; either from left or from right:
// {0, ..., 0} + data or data + {0, ..., 0}
// to choose the way, let's have a look at endiness
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
// A bit of reflection: let's find out suitable Converter method
var mi = typeof(BitConverter).GetMethod($"To{typeof(T).Name}");
if (null == mi)
throw new InvalidOperationException($"Type {typeof(T).Name} can't be converted");
else
return (T)(mi.Invoke(null, new object { data, 0 })); // or data.Length - size
}
Then you can use it as follow:
List<byte> varBytes = new List<byte>();
varBytes.Add(0x12);
varBytes.Add(0x34);
varBytes.Add(0x56);
varBytes.Add(0x78);
int result1 = GetTypedString<int>(varBytes);
long result2 = GetTypedString<long>(varBytes);
Console.WriteLine(result1.ToString("x"));
Console.WriteLine(result2.ToString("x"));
// How fast it is (Linq and Reflection?)
var sw = new System.Diagnostics.Stopwatch();
int n = 10000000;
sw.Start();
for (int i = 0; i < n; ++i) {
// The worst case:
// 1. We should expand the array
// 2. The output is the longest one
long result = GetTypedString<long>(varBytes);
//Trick: Do not let the compiler optimize the loop
if (result < 0)
break;
}
sw.Stop();
Console.WriteLine($"Microseconds per operation: {(sw.Elapsed.TotalSeconds/n*1000000)}");
Outcome:
78563412
78563412
Microseconds per operation: 0.84716933
Edit: If you insist on type name (string varType
) instead of generic parameter <T>
first of all let's extract a model (type name - type correspondense):
private static Dictionary<string, Type> s_Types =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) {
{ "uint16", typeof(UInt16)},
{ "ushort", typeof(UInt16)}, // <- you can add synonyms if you want
{ "int", typeof(Int32)},
{ "int32", typeof(Int32)},
{ "long", typeof(Int64)},
{ "int64", typeof(Int64)},
//TODO: add all the other names and correspondent types
};
Then you can implement it as
public static object GetTypedString(List<byte> varBytes, string varType) {
if (null == varBytes)
throw new ArgumentNullException(nameof(varBytes));
else if (null == varType)
throw new ArgumentNullException(nameof(varType));
Type type = null;
if (!s_Types.TryGetValue(varType, out type))
throw new ArgumentException(
$"Type name {varType} is not a valid type name.",
nameof(varBytes));
// sizeof alternative
// char is Ascii by default when marshalling; that's why Marshal.SizeOf returns 1
int size = typeof(T) == typeof(char)
? sizeof(char)
: System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
byte data = (size >= varBytes.Count)
? BitConverter.IsLittleEndian
? varBytes.Concat(new byte[size - varBytes.Count]).ToArray()
: new byte[size - varBytes.Count].Concat(varBytes).ToArray()
: varBytes.ToArray();
var mi = typeof(BitConverter).GetMethod($"To{type.Name}");
if (null == mi)
throw new InvalidOperationException(
$"Type {type.Name} (name: {varType}) can't be converted");
else
return mi.Invoke(null, new object { data, 0 }); // data.Length - size
}
Demo:
string result1 = (GetTypedString(varBytes, "Int64") as IFormattable).ToString("x8", null);
edited Nov 22 '18 at 7:30
answered Nov 20 '18 at 8:46


Dmitry BychenkoDmitry Bychenko
107k1093133
107k1093133
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than theswitch-case
method?
– abdullah cinar
Nov 20 '18 at 9:04
1
@abdullah cinar: it took about400 nanoseconds
per call (in case ofInt32
) and800 nanoseconds
in case of (Int64
) at my workstation (less than1 microsecond
in any case).
– Dmitry Bychenko
Nov 20 '18 at 9:29
1
@abdullah cinar: you can obtainType
from itsstring
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)
– Dmitry Bychenko
Nov 20 '18 at 12:00
1
@abdullah cinar: you are quite right,char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
– Dmitry Bychenko
Nov 22 '18 at 7:31
|
show 6 more comments
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than theswitch-case
method?
– abdullah cinar
Nov 20 '18 at 9:04
1
@abdullah cinar: it took about400 nanoseconds
per call (in case ofInt32
) and800 nanoseconds
in case of (Int64
) at my workstation (less than1 microsecond
in any case).
– Dmitry Bychenko
Nov 20 '18 at 9:29
1
@abdullah cinar: you can obtainType
from itsstring
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)
– Dmitry Bychenko
Nov 20 '18 at 12:00
1
@abdullah cinar: you are quite right,char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
– Dmitry Bychenko
Nov 22 '18 at 7:31
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
looks nice, but I won't recommend Reflection mostly for performance reasons.
– Sergiu Muresan
Nov 20 '18 at 8:51
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than the
switch-case
method?– abdullah cinar
Nov 20 '18 at 9:04
This is a bit more than I could do but I'm trying to understand it now. If I can get this work, it will be a shorter solution for me. But I don't know much about the performance issues. I'm running a data logger and speed is very important for me. Do you think this solution will be slower than the
switch-case
method?– abdullah cinar
Nov 20 '18 at 9:04
1
1
@abdullah cinar: it took about
400 nanoseconds
per call (in case of Int32
) and 800 nanoseconds
in case of (Int64
) at my workstation (less than 1 microsecond
in any case).– Dmitry Bychenko
Nov 20 '18 at 9:29
@abdullah cinar: it took about
400 nanoseconds
per call (in case of Int32
) and 800 nanoseconds
in case of (Int64
) at my workstation (less than 1 microsecond
in any case).– Dmitry Bychenko
Nov 20 '18 at 9:29
1
1
@abdullah cinar: you can obtain
Type
from its string
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)– Dmitry Bychenko
Nov 20 '18 at 12:00
@abdullah cinar: you can obtain
Type
from its string
name with a help of Dictionary<string, Type>` and then use the rest of the routine (see my edit, please)– Dmitry Bychenko
Nov 20 '18 at 12:00
1
1
@abdullah cinar: you are quite right,
char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…– Dmitry Bychenko
Nov 22 '18 at 7:31
@abdullah cinar: you are quite right,
char
is an exceptional case docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…– Dmitry Bychenko
Nov 22 '18 at 7:31
|
show 6 more comments
Rather than using .ToArray
you could preallocate your array to the correct size and use .CopyTo
.
Example:
var byteArray = new byte[sizeof(UInt32)];
varBytes.CopyTo(byteArray);
UInt32 varReady = BitConverter.ToUInt32(byteArray, 0);
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
add a comment |
Rather than using .ToArray
you could preallocate your array to the correct size and use .CopyTo
.
Example:
var byteArray = new byte[sizeof(UInt32)];
varBytes.CopyTo(byteArray);
UInt32 varReady = BitConverter.ToUInt32(byteArray, 0);
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
add a comment |
Rather than using .ToArray
you could preallocate your array to the correct size and use .CopyTo
.
Example:
var byteArray = new byte[sizeof(UInt32)];
varBytes.CopyTo(byteArray);
UInt32 varReady = BitConverter.ToUInt32(byteArray, 0);
Rather than using .ToArray
you could preallocate your array to the correct size and use .CopyTo
.
Example:
var byteArray = new byte[sizeof(UInt32)];
varBytes.CopyTo(byteArray);
UInt32 varReady = BitConverter.ToUInt32(byteArray, 0);
answered Nov 20 '18 at 8:35
LoocidLoocid
2,61911230
2,61911230
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
add a comment |
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
1
1
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
you need to validate the length of the varBytes list. If there are more than 4 bytes in this list then you'll get the error: "Destination array was not long enough. " because you are trying to copy a, lets say, 8 bytes array over a 4 bytes array.
– Sergiu Muresan
Nov 20 '18 at 9:10
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
Yes, I just got that error. So now the initial problem just changed the way. I don't want to add a condition for every data type because I will have at least 10 different data types.
– abdullah cinar
Nov 20 '18 at 9:15
add a comment |
You can check for the length of the array and convert it to smaller types then cast the required one
case "uint32":
{
if (varBytes.Count == 1)
{
varReady = (UInt32)varBytes[0];
}
else if (varBytes.Count >= 2 && varBytes.Count < 4)
{
varReady = (UInt32)BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
}
else
{
varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
}
break;
}
Thanks, but if the user wants to convert them toUInt64
, I will need to add another condition too.
– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
add a comment |
You can check for the length of the array and convert it to smaller types then cast the required one
case "uint32":
{
if (varBytes.Count == 1)
{
varReady = (UInt32)varBytes[0];
}
else if (varBytes.Count >= 2 && varBytes.Count < 4)
{
varReady = (UInt32)BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
}
else
{
varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
}
break;
}
Thanks, but if the user wants to convert them toUInt64
, I will need to add another condition too.
– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
add a comment |
You can check for the length of the array and convert it to smaller types then cast the required one
case "uint32":
{
if (varBytes.Count == 1)
{
varReady = (UInt32)varBytes[0];
}
else if (varBytes.Count >= 2 && varBytes.Count < 4)
{
varReady = (UInt32)BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
}
else
{
varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
}
break;
}
You can check for the length of the array and convert it to smaller types then cast the required one
case "uint32":
{
if (varBytes.Count == 1)
{
varReady = (UInt32)varBytes[0];
}
else if (varBytes.Count >= 2 && varBytes.Count < 4)
{
varReady = (UInt32)BitConverter.ToUInt16(varBytes.ToArray<byte>(), 0);
}
else
{
varReady = BitConverter.ToUInt32(varBytes.ToArray<byte>(), 0);
}
break;
}
edited Nov 20 '18 at 8:54
answered Nov 20 '18 at 8:42


Sergiu MuresanSergiu Muresan
3246
3246
Thanks, but if the user wants to convert them toUInt64
, I will need to add another condition too.
– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
add a comment |
Thanks, but if the user wants to convert them toUInt64
, I will need to add another condition too.
– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
Thanks, but if the user wants to convert them to
UInt64
, I will need to add another condition too.– abdullah cinar
Nov 20 '18 at 8:58
Thanks, but if the user wants to convert them to
UInt64
, I will need to add another condition too.– abdullah cinar
Nov 20 '18 at 8:58
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
yes, that is the other case
– Sergiu Muresan
Nov 20 '18 at 8:59
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388775%2fadd-range-dynamically-to-list%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Your
GetTypedString
method will not compile.– SeM
Nov 20 '18 at 8:24
Sorry, I had simplified the code to paste here. I added
return
value and it should be okay now.– abdullah cinar
Nov 20 '18 at 8:27
it seems to be working, it returns 2018915346 dotnetfiddle.net/4gCLmm
– Sergiu Muresan
Nov 20 '18 at 8:29
yes, it works very well but I was curious about if it is possible to do it easier and faster to convert.
– abdullah cinar
Nov 20 '18 at 8:31
Does the byte array originate from an
UInt32
? If so, why didn't you save the original two zero bytes? If not, why don't you solve this at the output side by casting?– CodeCaster
Nov 20 '18 at 8:32