Converting sbyte[] to byte[]

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using binary writer to write an array of bytes to disk. However, my data starts out as an array of sbytes. I am currently type casting each array element in a for loop. Is there a faster method for converting an array of sbytes to an array of bytes?

Thanks,
Darrel
 
Array.Copy will often perform conversions for you. However, in this case, it
doesn't
appear that it will, so that won't be an option. The problem is the conversion
is considered
narrowing, since you'll lose any negative numbers. I guess doing a blind memory
copy
wasn't in their plans.

I think Buffer.BlockCopy will do what you need though. You should check it out
and see
if it works in your scenario...

using System;

public class SByteToByte {
private static void Main(string[] args) {
sbyte[] sbytes = new sbyte[10];
byte[] bytes = new byte[10];

for(int i = 0; i < sbytes.Length; i++) {
sbytes = (sbyte) (i - 5);
Console.WriteLine(sbytes);
}
Console.WriteLine();

Buffer.BlockCopy(sbytes, 0, bytes, 0, bytes.Length);
for(int i = 0; i < bytes.Length; i++) {
Console.WriteLine(bytes);
}
Console.WriteLine();

Buffer.BlockCopy(bytes, 0, sbytes, 0, bytes.Length);
for(int i = 0; i < sbytes.Length; i++) {
Console.WriteLine(sbytes);
}
Console.WriteLine();
}
}


--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

Darrel said:
I am using binary writer to write an array of bytes to disk. However, my data
starts out as an array of sbytes. I am currently type casting each array
element in a for loop. Is there a faster method for converting an array of
sbytes to an array of bytes?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top