I'm passing int[] array that hold image, later I want to convert it to bytes[] and save the image to local path. However, I notice that the bytePic[] length is equal to int[] arrPic just the values are missing. There is a screenshot below:
Below is the entire function:
public string ChangeMaterialPicture(int[] arrPic, int materialId,string defaultPath)
{
var material = _warehouseRepository.GetMaterialById(materialId);
if(material is not null)
{
// Convert the Array to Bytes
byte[] bytePic = new byte[arrPic.Length];
for(var i = 0; i < arrPic.Length; i++)
{
AddByteToArray(bytePic, Convert.ToByte(arrPic[i]));
}
// Convert the Bytes to IMG
string filename = Guid.NewGuid().ToString() + "_.png";
System.IO.File.WriteAllBytes(#$"{defaultPath}\materials\{material.VendorId}\{filename}", bytePic);
// Update the Image
material.Picture = filename;
_warehouseRepository.UpdateMaterial(material);
return material.Picture;
}
else
{
return String.Empty;
}
}
public byte[] AddByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
You are creating the new array newArray in AddByteToArray and return it. But at the call site you are never using this returned value and the bytePic array remains unchanged.
The code in AddByteToArray makes no sense. Why create a new array when the intention was to insert one byte into an existing array? What you need to do is to cast the int into byte. Simply write:
byte[] bytePic = new byte[arrPic.Length];
for (int i = 0; i < arrPic.Length; i++)
{
bytePic[i] = (byte)arrPic[i];
}
And delete the method AddByteToArray.
This assumes that every value in the int array is in the range 0 to 255 and therefore fits into one byte.
There are different ways to do this. With LINQ you could also write:
byte[] bytePic = arrPic.Select(i => (byte)i).ToArray();
I would assume your original array uses a int to represent a full RGBA-pixel, since 32bit per pixel mono images are very rare in my experience. And if you do have such an image, you probably want to be more intelligent in how you do this conversion. The only time just casting int to bytes would be a good idea is if you are sure only the lower 8 bits are used, but if that is the case, why are you using an int-array in the first place.
If you actually have RGBA-pixles you do not want to convert individual int-values to bytes, but rather convert a single int value to 4 bytes. And this is not that difficult to do, you just need to use the right methods. The old school options is to use Buffer.BlockCopy.
Example:
byte[] bytePic = new byte[arrPic.Length * 4];
Buffer.BlockCopy(arrPic, 0, bytePic, 0, bytePic.Length);
But if your write-method accepts a span you might want to just convert your array to a span and cast this to the right type, avoiding the copy.
I have some code that converts a float[] to a Base64 string:
float[] f_elements = <from elsewhere in my code>;
byte[] f_vfeat = f_elements.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
string f_sig = Convert.ToBase64String(f_vfeat);
I also have - basically - the same code that converts an int[] to a Base64 string:
int[] i_elements = <from elsewhere in my code>;
byte[] i_feat = i_elements.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
string i_sig = Convert.ToBase64String(i_feat);
Both of these produce Base64 strings as expected. However, now I need to decode back to an array, and I'm running into trouble.
How can I go from my Base64 string(s), and get the original data array(s). Before I decode the Base64 string, I will know if it is suppose to be an int[] or float[], so I think that will help.
Does anyone know how to do go from Base64 string to float[] or int[]?
You can use BitConverter.ToInt32 or BitConverter.ToSingle to convert part of an array:
byte[] bytes = Convert.FromBase64String();
int[] ints = new int[bytes.Length / 4];
for (int i = 0; i < ints.Length; i++)
{
ints[i] = BitConverter.ToInt32(bytes, i * 4);
}
(And the equivalent for ToSingle, of course.)
In my view, it's a shame that GetBytes doesn't have an overload to write the bytes directly into an existing array, instead of creating a new array on each call...
Is there something wrong with Convert.FromBase64String?
byte[] i_feat = Convert.FromBase64String(i_sig)
I am having the problem that whitespace of some sort is being inserted between characters when I am converting a Queue<byte> list into a string for comparison. I do not think that they are actual whitespace characters, however, because the Queue retains only seven values and when debugging I am still able to see the seven character values. See image:
Relevant code:
Queue<byte> bufKeyword = new Queue<byte>(7);
// Remove old byte from queue and add new one
if (bufKeyword.Count == 7) bufKeyword.Dequeue();
bufKeyword.Enqueue((byte)fsInput.ReadByte());
// Check buffer string for match
StringBuilder bufKeywordString = new StringBuilder();
foreach (byte qByte in bufKeyword) {
bufKeywordString.Append(Encoding.ASCII.GetString(BitConverter.GetBytes(qByte)));
}
string _bufKeywordString = bufKeywordString.ToString();
Console.WriteLine("{0}", _bufKeywordString); //DEBUG - SEE IMAGE
StringBuilder bufWriteString = new StringBuilder();
if (_bufKeywordString.StartsWith("time=")) //Does not work because of 'whitespace'
{
for (int i = 1; i < 25; i++) { bufWriteString.Append(fsInput.ReadByte()); } // Read next 24 bytes
fileWriteQueue.Enqueue(bufWriteString.ToString()); // Add this data to write queue
fileWriteQueueCount++;
fileBytesRead += 24; // Change to new spot in file
}
There is no BitConverter.GetBytes for byte argument. byte gets converted to short, and BitConverter.GetBytes(short) returns an array of two elements.
So instead of
bufKeywordString.Append(Encoding.ASCII.GetString(BitConverter.GetBytes(qByte)));
try
bufKeywordString.Append(Encoding.ASCII.GetString(new byte[] {qByte});
I want to transmit one APDU and I get back the response. I want to check the last two bytes by an API which will log the comparison.
byte[] response = Transmit(apdu);
//response here comes will be 0x00 0x01 0x02 0x03 0x04
//response.Length will be 5
byte[] expectedResponse = { 0x03, 0x04 };
int index = (response.Length)-2;
Log.CheckLastTwoBytes(response[index],expectedResponse);
//The declaration of CheckLastTwoBytes is
//public static void CheckLastTwoBytes(byte[] Response, byte[] ExpResp)
This is an error of invalid arguments. How can I pass the last 2 bytes to APIs?
Use Array.Copy
byte[] newArray = new byte[2];
Array.Copy(response, response.Length-2, newArray, 2);
Log.CheckLastTwoBytes(newArray,expectedResponse);
new ArraySegment<byte>(response, response.Length - 2, 2).Array
EDIT: nevermind this, apparently .Array just returns the original entire array and not the slice. You would have to modify your other method to accept ArraySegment instead of byte[]
Since the type of response[index] is byte (not byte[]), it's not surprising that you'd get that error.
If Log.CheckLastTwoBytes really does check just the last two bytes of its Response parameter, then you should just pass response:
Log.CheckLastTwoBytes(response, expectedResponse)
You can't have a subarray just like that, no...
First solution, obvious one:
var tmp = new byte[] { response[response.Length - 2],
response[response.Length - 1] };
Log.CheckLastTwoBytes(tmp, expectedResponse);
Or, you could do this:
response[0] = response[response.Length - 2];
response[1] = response[response.Length - 1];
Log.CheckLastTwoBytes(response, expectedResponse);
It might be that this function doesn't check for exact lengths, etc, so you could just put the last two bytes as the first two, if you don't care about destroying the data.
Or, alternatively, you can use linq:
byte[] lastTwoBytes = response.Skip(response.Length-2).Take(2).ToArray();
This question already has answers here:
What is the equivalent of memset in C#?
(17 answers)
Closed 8 years ago.
I'm busy rewriting an old project that was done in C++, to C#.
My task is to rewrite the program so that it functions as close to the original as possible.
During a bunch of file-handling the previous developer who wrote this program creates a structure containing a ton of fields that correspond to the set format that a file has to be written in, so all that work is already done for me.
These fields are all byte arrays. What the C++ code then does is use memset to set this entire structure to all spaces characters (0x20). One line of code. Easy.
This is very important as the utility that this file eventually goes to is expecting the file in this format. What I've had to do is change this struct to a class in C#, but I cannot find a way to easily initialize each of these byte arrays to all space characters.
What I've ended up having to do is this in the class constructor:
//Initialize all of the variables to spaces.
int index = 0;
foreach (byte b in UserCode)
{
UserCode[index] = 0x20;
index++;
}
This works fine, but I'm sure there must be a simpler way to do this. When the array is set to UserCode = new byte[6] in the constructor the byte array gets automatically initialized to the default null values. Is there no way that I can make it become all spaces upon declaration, so that when I call my class' constructor that it is initialized straight away like this? Or some memset-like function?
For small arrays use array initialisation syntax:
var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
For larger arrays use a standard for loop. This is the most readable and efficient way to do it:
var sevenThousandItems = new byte[7000];
for (int i = 0; i < sevenThousandItems.Length; i++)
{
sevenThousandItems[i] = 0x20;
}
Of course, if you need to do this a lot then you could create a helper method to help keep your code concise:
byte[] sevenItems = CreateSpecialByteArray(7);
byte[] sevenThousandItems = CreateSpecialByteArray(7000);
// ...
public static byte[] CreateSpecialByteArray(int length)
{
var arr = new byte[length];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = 0x20;
}
return arr;
}
Use this to create the array in the first place:
byte[] array = Enumerable.Repeat((byte)0x20, <number of elements>).ToArray();
Replace <number of elements> with the desired array size.
You can use Enumerable.Repeat()
Enumerable.Repeat generates a sequence that contains one repeated value.
Array of 100 items initialized to 0x20:
byte[] arr1 = Enumerable.Repeat((byte)0x20,100).ToArray();
var array = Encoding.ASCII.GetBytes(new string(' ', 100));
If you need to initialise a small array you can use:
byte[] smallArray = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
If you have a larger array, then you could use:
byte[] bitBiggerArray Enumerable.Repeat(0x20, 7000).ToArray();
Which is simple, and easy for the next guy/girl to read. And will be fast enough 99.9% of the time.
(Normally will be the BestOption™)
However if you really really need super speed, calling out to the optimized memset method, using P/invoke, is for you:
(Here wrapped up in a nice to use class)
public static class Superfast
{
[DllImport("msvcrt.dll",
EntryPoint = "memset",
CallingConvention = CallingConvention.Cdecl,
SetLastError = false)]
private static extern IntPtr MemSet(IntPtr dest, int c, int count);
//If you need super speed, calling out to M$ memset optimized method using P/invoke
public static byte[] InitByteArray(byte fillWith, int size)
{
byte[] arrayBytes = new byte[size];
GCHandle gch = GCHandle.Alloc(arrayBytes, GCHandleType.Pinned);
MemSet(gch.AddrOfPinnedObject(), fillWith, arrayBytes.Length);
gch.Free();
return arrayBytes;
}
}
Usage:
byte[] oneofManyBigArrays = Superfast.InitByteArray(0x20,700000);
Maybe these could be helpful?
What is the equivalent of memset in C#?
http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html
Guys before me gave you your answer. I just want to point out your misuse of foreach loop. See, since you have to increment index standard "for loop" would be not only more compact, but also more efficient ("foreach" does many things under the hood):
for (int index = 0; index < UserCode.Length; ++index)
{
UserCode[index] = 0x20;
}
This is a faster version of the code from the post marked as the answer.
All of the benchmarks that I have performed show that a simple for loop that only contains something like an array fill is typically twice as fast if it is decrementing versus if it is incrementing.
Also, the array Length property is already passed as the parameter so it doesn't need to be retrieved from the array properties. It should also be pre-calculated and assigned to a local variable.
Loop bounds calculations that involve a property accessor will re-compute the value of the bounds before each iteration of the loop.
public static byte[] CreateSpecialByteArray(int length)
{
byte[] array = new byte[length];
int len = length - 1;
for (int i = len; i >= 0; i--)
{
array[i] = 0x20;
}
return array;
}
Just to expand on my answer a neater way of doing this multiple times would probably be:
PopulateByteArray(UserCode, 0x20);
which calls:
public static void PopulateByteArray(byte[] byteArray, byte value)
{
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] = value;
}
}
This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)
The fastest way to do this is to use the api:
bR = 0xFF;
RtlFillMemory(pBuffer, nFileLen, bR);
using a pointer to a buffer, the length to write, and the encoded byte. I think the fastest way to do it in managed code (much slower), is to create a small block of initialized bytes, then use Buffer.Blockcopy to write them to the byte array in a loop. I threw this together but haven't tested it, but you get the idea:
long size = GetFileSize(FileName);
// zero byte
const int blocksize = 1024;
// 1's array
byte[] ntemp = new byte[blocksize];
byte[] nbyte = new byte[size];
// init 1's array
for (int i = 0; i < blocksize; i++)
ntemp[i] = 0xff;
// get dimensions
int blocks = (int)(size / blocksize);
int remainder = (int)(size - (blocks * blocksize));
int count = 0;
// copy to the buffer
do
{
Buffer.BlockCopy(ntemp, 0, nbyte, blocksize * count, blocksize);
count++;
} while (count < blocks);
// copy remaining bytes
Buffer.BlockCopy(ntemp, 0, nbyte, blocksize * count, remainder);
This function is way faster than a for loop for filling an array.
The Array.Copy command is a very fast memory copy function. This function takes advantage of that by repeatedly calling the Array.Copy command and doubling the size of what we copy until the array is full.
I discuss this on my blog at https://grax32.com/2013/06/fast-array-fill-function-revisited.html (Link updated 12/16/2019). Also see Nuget package that provides this extension method. http://sites.grax32.com/ArrayExtensions/
Note that this would be easy to make into an extension method by just adding the word "this" to the method declarations i.e. public static void ArrayFill<T>(this T[] arrayToFill ...
public static void ArrayFill<T>(T[] arrayToFill, T fillValue)
{
// if called with a single value, wrap the value in an array and call the main function
ArrayFill(arrayToFill, new T[] { fillValue });
}
public static void ArrayFill<T>(T[] arrayToFill, T[] fillValue)
{
if (fillValue.Length >= arrayToFill.Length)
{
throw new ArgumentException("fillValue array length must be smaller than length of arrayToFill");
}
// set the initial array value
Array.Copy(fillValue, arrayToFill, fillValue.Length);
int arrayToFillHalfLength = arrayToFill.Length / 2;
for (int i = fillValue.Length; i < arrayToFill.Length; i *= 2)
{
int copyLength = i;
if (i > arrayToFillHalfLength)
{
copyLength = arrayToFill.Length - i;
}
Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
}
}
You can use a collection initializer:
UserCode = new byte[]{0x20,0x20,0x20,0x20,0x20,0x20};
This will work better than Repeat if the values are not identical.
You could speed up the initialization and simplify the code by using the the Parallel class (.NET 4 and newer):
public static void PopulateByteArray(byte[] byteArray, byte value)
{
Parallel.For(0, byteArray.Length, i => byteArray[i] = value);
}
Of course you can create the array at the same time:
public static byte[] CreateSpecialByteArray(int length, byte value)
{
var byteArray = new byte[length];
Parallel.For(0, length, i => byteArray[i] = value);
return byteArray;
}