Click here to Skip to main content
15,891,633 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have this function which append an array of byte to an other array of bytes
but the problem appears when the source contains '\0'
this what I have :

C#
private void Aes_Strcat(sbyte[] a_pchResult, sbyte[] pchResult, int m_iBlockSize)
        {
            int x = 0;
            while (a_pchResult[x] != 0)
            {
                x++;
            }

            Buffer.BlockCopy(pchResult, 0, a_pchResult, x, m_iBlockSize);
        }


here when the a_pchResult contains for example { -10, 15,3,45,17,25,0,56,41,12,0,0,0,0,0,0}
and I want to add pchResult to it at the end (it means after the '12' element)
but as you say it will add it after '25' because it find the '0' before the end.

any idea how know the last position to add the new array at the end of source array if it contains '\0' element.
Posted
Updated 28-Apr-15 23:32pm
v2

Byte data isn't normally terminated by a '\0' character - that's a perfectly normal, and acceptable binary value in the range 0 to 255 inclusive! '\0' is not used as a terminator in .NET data at all - it comes from the C and C++ world.
Normally, you would pass the "used" length of the output array - if you don't you will overwrite the wrong data.
 
Share this answer
 
I'd suggest you make a class containing the array, an offset-counter and methods for merging it with another array or instance of the same class.

Please ask if something shouldn't be clear - I have the impression you would know what I mean, just hanging on to some C mindset still :)

edit: The result would then be something similar to MemoryStream[^]
 
Share this answer
 
v2
This would be nothing but abuse, big abuse. The "termination" approach on strings and arrays was really nasty in first place. In decent systems and languages, more modern and refined ones, people when away from this apparent lame completely. Arrays and list are self-contained objects which carry all one would need to work with then, first of all, their length. If you work with an array, you initialize it with some length, which is kept remembered in the array object itself:
C#
int length = //...
sbyte[] array = new sbyte[length];

//...

for (int index = 0; index < array.Length; ++index) {
    // array.Length == length
}

Similar thing goes for arrays of higher rank, arrays with not zero-base indices (see Array.GetLowerBound, Array.GetUpperBound), and so on:
https://msdn.microsoft.com/en-us/library/system.array%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.array.getlowerbound(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.array.getupperbound(v=vs.110).aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900