Calculating the mode of an array containing hex values? - c#

I am programming in C#.
I've been experimenting with some code that calculates the mode of an array containing integers. i.e given {5,6,2,1,5} the mode is 5.
My questions is, can this be done with hex values?
For example, lets say I had the following array:
unsigned char HEXVALUES[ ] = {0x66, 0x60, 0xe7, 0xf0, 0x66};
How could I go about writing a program that tells me that 0x66 is the mode?
I've thought about converting them to decimal values and finding the mode that way, but it seems inefficient.
Thanks

Hexadecimal value is just a representation of numeric value. E.g. these all are representations of same decimal value 102:
66 (Hex)
102 (Dec)
01100110 (Bin)
So just create array of integer values written in Hexadecimal format and make your calculations like with any other integer values:
var array = new[] { 0x66, 0x60, 0xe7, 0xf0, 0x66 };
var mode = array.GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key;
Console.WriteLine($"{mode:X}"); // output int as hex

I suppose the mode of any collection is
theCollection
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(g => g.FirstOrDefault())
.First()

"Hex numbers" are the same thing as integers. The difference is the way they are represented visually (in code, and when converted to strings). In binary they are exactly the same.
So whatever code you used before on
unsigned char[] list = new char[]{5,6,2,1,5};
FindMode(list);
will work identically with
unsigned char[] list = new char[]{0x66, 0x60, 0xe7, 0xf0, 0x66};
FindMode(list);

Related

Why do I not get the correct value when converting 4 bytes to an int

So I'm currently learning about little endian, big endian, hex and binary.
At the moment I have this array of bytes, represented in hex new byte[] { 0x06, 0x1B, 0x0A, 0xFF }; and if I try to get the int value, by reading it using little endian
int theValue = BitConverter.ToInt32(arr.Reverse().ToArray(), 0);
it gives me the correct value which is 102,435,583
however.. if I remove .Reverse().ToArray() aka read it as big endian, it gives me a negative value, since technically it exceeds the maximum value of an integer. The value I'm trying to get is 4,283,488,352.. I figured I would be able to just cast it as a uint by doing so
uint theValue = (uint)BitConverter.ToInt32(arr, 0); I get this value 4,278,852,358 which as you can see is not correct.. It's close but not correct, and I've been told that this is because something overflows but I'm not sure what that means.
Why am I not getting the value 4,283,488,352 but rather a different (wrong) value 4,278,852,358

how to extract two components from HEX string , reverse XOR

My I need to generate a random 32 char HEX string. I have code in place that will generate for example E272E28B8961FB155E3FC657831F0690
Now, I need to break this down into two 32 char strings such that value of string 1 XOR string 2 will = E272E28B8961FB155E3FC657831F0690
I seem to be having a hard time wrapping my head around that. I suppose I need a reverse XOR on this string. Any suggestions on how to accomplish this?
Assuming that you want two 32 Hexadecimal Character strings (which is equivalent to 16 bytes) which will XOR to a known 32 Hexadecimal Character string, you can use this method.
Generate random bytes for the first part of the output, then calculate what the second part has to be based on the first part and the expected output. XOR is a self-inverting operator (there's a fancy word for that that I'm forgetting) so it's fairly straightforward to do.
void q50415070()
{
var random = new Random();
var output = new byte[16];
random.NextBytes(output);
Debug.WriteLine(BitConverter.ToString(output));
// 91-77-E9-2F-EC-F7-8E-CC-03-AF-37-FD-4F-6F-D2-4D
var part1 = new byte[16];
random.NextBytes(part1);
Debug.WriteLine(BitConverter.ToString(part1));
// 7A-9B-2B-8B-D7-CE-AA-7E-7E-C3-FE-FF-44-2A-21-3C
var part2 = part1.Zip(output, (x, y) => (byte)(x ^ y)).ToArray();
Debug.WriteLine(BitConverter.ToString(part2));
// EB-EC-C2-A4-3B-39-24-B2-7D-6C-C9-02-0B-45-F3-71
}
In this, output is the result I'm trying to reach, and part1 and part2 are the two components that I want to be able to XOR together to get the expected output.
I've used the Linq Zip method to combine the two IEnumerable<byte>s together element by element, then used the XOR operator ^ to calculate the result byte-by-byte. Finally calling ToArray() to make it back into an array at the end.
This technique is used often in cryptography where you want to split an encryption key into two parts for two people to have, each of which is useless by itself.
Edit: Tweaked the function slightly to more closely match your question:
void q50415070()
{
var output = new byte[16] { 0xE2, 0x72, 0xE2, 0x8B, 0x89, 0x61, 0xFB, 0x15, 0x5E, 0x3F, 0xC6, 0x57, 0x83, 0x1F, 0x06, 0x90 };
Debug.WriteLine(BitConverter.ToString(output));
// E2-72-E2-8B-89-61-FB-15-5E-3F-C6-57-83-1F-06-90
var random = new Random();
var part1 = new byte[16];
random.NextBytes(part1);
Debug.WriteLine(BitConverter.ToString(part1));
// 59-37-D0-A6-71-CC-6C-17-96-02-70-CE-A7-57-06-25
var part2 = part1.Zip(output, (x, y) => (byte)(x ^ y)).ToArray();
Debug.WriteLine(BitConverter.ToString(part2));
// BB-45-32-2D-F8-AD-97-02-C8-3D-B6-99-24-48-00-B5
}
Hope this helps

From hex string to byteArray C#

I have in input the string: "0080801D803480002A1168301FE16E09"
and when i convert it to byteArray with the code:
Convert.ToByte(inputWrite.Substring(i, 2), 16);
I get the byte array in first position = "0", but i need to have "00", so when i convert it again into a String a don't get "08" but "00" at the begining.
i get in the and the string "080801D80348002A1168301FE16E9" and like this i'm missing some important 0, that i need to convert then from this last string to byte again and to decimal values.
Once you have your byes in an array, there's no difference between 0 and 00.
What you need to do is, when converting those bytes back to a string, make sure you put any leading zeros back in. You can do this by calling
string byteAsTwoDigitString = myByte.ToString("X2");
The X says "as hexadecimal", the 2 says "with at least two digits".
You can also do this using LINQ:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
You can also refer this
You seem to be confusing things. Because each byte is represented by two characters, bytes array will be two times shorter than the string. When parsing back, you have to make sure that each byte must be converted to two-characters string, even if it is less than 0x10, i.e. does not require second character.
That said, you can use following LINQ oneliner:
string convertedBack = string.Join(string.Empty, bytes.Select(x => x.ToString("X2")).ToArray());

Convert int array to string in C#

I have an int[]:
RXBuffer[0], RXBuffer[1],..., RXBuffer[9]
where each value represents an ASCII code, so 0x31 represents 1, 0x41 represents A.
How do I convert this to a 10 character string ?
So far I've tried Data = RxBuffer.ToString();. But it shows Data equals to System.Int32[] which is not what my data is.
How can I do this?
Assuming the "int array" is values in the 0-9 range (which is the only way that makes sense to convert an "int array" length 10 to a 10-character string) - a bit of an exotic way:
string s = new string(Array.ConvertAll(RXBuffer, x => (char)('0' + x)));
But pretty efficient (the char[] is right-sized automatically, and the string conversion is done just with math, instead of ToString()).
Edit: with the revision that makes it clear that these are actually ASCII codes, it becomes simpler:
string s = new string(Array.ConvertAll(RXBuffer, x => (char)x));
Although frankly, if the values are ASCII (or even unicode) it would be better to store it as a char[]; this covers the same range, takes half the space, and is just:
string s = new string(RXBuffer);
LolCoder
All you need is :
string.Join("",RXBuffer);
============== Or =================
int[] RXBuffer = {0,1,2,3,4,5,6,7,8,9};
string result = string.Join(",",RXBuffer);

Problem in converting sprintf to C#

i have this line I need to write in C#
sprintf(
currentTAG,
"%2.2X%2.2X,%2.2X%2.2X",
hBuffer[ presentPtr+1 ],
hBuffer[ presentPtr ],
hBuffer[ presentPtr+3 ],
hBuffer[ presentPtr+2 ] );
hbuffer is a uchar array.
In C# I have the same data in a byte array and I need to implement this line...
Please help...
Check if this works:
byte[] hBuffer = { ... };
int presentPtr = 0;
string currentTAG = string.Format("{0:X2}{1:X2},{2:X2}{3:X2}",
hBuffer[p+1],
hBuffer[p],
hBuffer[p + 3],
hBuffer[p + 2]);
This is another option but less efficient:
byte[] hBuffer = { ... };
int presentPtr = 0;
string currentTAG = string.Format("{0}{1},{2}{3}",
hBuffer[p+1].ToString("X2"),
hBuffer[p].ToString("X2"),
hBuffer[p + 3].ToString("X2"),
hBuffer[p + 2].ToString("X2"));
Converting each byte of hBuffer to a
string, as in the second example, is
less efficient. The first example will
give you better performance,
especially if you do this many times,
by virtue of not spamming the garbage
collector.
[From the top of my head] In C/C++ %2.2X outputs the value in hexadecimal using upper case letters and at least two letters (left padded with zero).
In C++ the next example outputs 01 61 in the console:
unsigned char test[] = { 0x01, 'a' };
printf("%2.2X %2.2X", test[0], test[1]);
Using the information above, the following C# snippet outputs also 01 61 in the console:
byte[] test = { 0x01, (byte) 'a' };
Console.WriteLine(String.Format("{0:X2} {1:X2}", test[0], test[1]));
Composite Formatting: This page discusses how to use the string.Format() function.
You are looking for String.Format method.

Categories