I have a string,
string Var="11001100"
I want to convert it into a byte array.
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
Can anybody guide me in this? I tried the following code, but I get the data in ASCII. I do not want that.
bArray = Encoding.Default.GetBytes(var);
I suggest using Linq:
using System.Linq;
...
string Var = "11001100";
byte[] bArray = Var
.Select(item => (byte) (item == '0' ? 1 : 0))
.ToArray();
Test:
Console.WriteLine(string.Join(Environment.NewLine, bArray
.Select((value, index) => $"bArray[{index}]=0x{value:X2};")));
Outcome:
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
but I get the data in ASCII. I do not want that.
Then you need the string representation of the chars. You get it using the ToString method. This would be the old scool way simply using a reversed for-loop:
string Var="11001100";
byte [] bArray = new byte[Var.Length];
int countForward = 0;
for (int i = Var.Length-1; i >= 0 ; i--)
{
bArray[countForward] = Convert.ToByte(Var[i].ToString());
countForward++;
}
This is my solution for your question:
string value = "11001100";
int numberOfBits = value.Length;
var valueAsByteArray = new byte[numberOfBits];
for (int i = 0; i < numberOfBits; i++)
{
bytes[i] = ((byte)(value[i] - 0x30)) == 0 ? (byte)1 : (byte)0;
}
Edit: Forgot the inversion.
Related
I have String array named "string_array_packet" which contains
FA,11,1,4,90,6C,E7,72,0,0,0,8,80,0,8,80,7B,
Now i need to copy the contents between first and last index of array and store it in another array and then need to prefix 0 to single digits
11,1,4,90,6C,E7,72,0,0,0,8,80,0,8,80,
What I have done so far is
var sourceStartIndex = 1;
var destinationLength = string_array_packet.Length - 2;
Console.WriteLine(string_array_packet.Length);
Console.WriteLine(destinationLength);
var destinationStartIndex = 0;
var destination = new string[destinationLength];
Array.Copy(string_array_packet, sourceStartIndex,
destination, destinationStartIndex, destinationLength);
Not sure how to proceed after this.
This can be done much easier with Linq (using System.Linq required):
var sourceStartIndex = 1;
var destinationLength = string_array_packet.Length - 2;
var strings = string_array_packet.Skip(sourceStartIndex)
.Select(x => x.Length == 1 ? "0" + x :x)
.Take(destinationLength)
.ToArray();
Alternatively, if you're not familiar with the Enumerable methods then add the following imperative approach to complete your code:
for (int i = 0; i < destination.Length; i++)
if (destination[i].Length == 1)
destination[i] = "0" + destination[i];
I am trying to work through a scenario I haven't seen before and am struggling to come up with an algorithm to implement this properly. Part of my problem is a hazy recollection of the proper terminology. I believe what I am needing is a variation of the standard "combination" problem, but I could well be off there.
The Scenario
Given an example string "100" (let's call it x), produce all combinations of x that swap out one of those 0 (zero) characters for a o (lower-case o). So, for the simple example of "100", I would expect this output:
"100"
"10o"
"1o0"
"1oo"
This would need to support varying length strings with varying numbers of 0 characters, but assume there would never be more than 5 instances of 0.
I have this very simple algorithm that works for my sample of "100" but falls apart for anything longer/more complicated:
public IEnumerable<string> Combinations(string input)
{
char[] buffer = new char[input.Length];
for(int i = 0; i != buffer.Length; ++i)
{
buffer[i] = input[i];
}
//return the original input
yield return new string(buffer);
//look for 0's and replace them
for(int i = 0; i != buffer.Length; ++i)
{
if (input[i] == '0')
{
buffer[i] = 'o';
yield return new string(buffer);
buffer[i] = '0';
}
}
//handle the replace-all scenario
yield return input.Replace("0", "o");
}
I have a nagging feeling that recursion could be my friend here, but I am struggling to figure out how to incorporate the conditional logic I need here.
Your guess was correct; recursion is your friend for this challenge. Here is a simple solution:
public static IEnumerable<string> Combinations(string input)
{
int firstZero = input.IndexOf('0'); // Get index of first '0'
if (firstZero == -1) // Base case: no further combinations
return new string[] { input };
string prefix = input.Substring(0, firstZero); // Substring preceding '0'
string suffix = input.Substring(firstZero + 1); // Substring succeeding '0'
// e.g. Suppose input was "fr0d00"
// Prefix is "fr"; suffix is "d00"
// Recursion: Generate all combinations of suffix
// e.g. "d00", "d0o", "do0", "doo"
var recursiveCombinations = Combinations(suffix);
// Return sequence in which each string is a concatenation of the
// prefix, either '0' or 'o', and one of the recursively-found suffixes
return
from chr in "0o" // char sequence equivalent to: new [] { '0', 'o' }
from recSuffix in recursiveCombinations
select prefix + chr + recSuffix;
}
This works for me:
public IEnumerable<string> Combinations(string input)
{
var head = input[0] == '0' //Do I have a `0`?
? new [] { "0", "o" } //If so output both `"0"` & `"o"`
: new [] { input[0].ToString() }; //Otherwise output the current character
var tails = input.Length > 1 //Is there any more string?
? Combinations(input.Substring(1)) //Yes, recursively compute
: new[] { "" }; //Otherwise, output empty string
//Now, join it up and return
return
from h in head
from t in tails
select h + t;
}
You don't need recursion here, you can enumerate your patterns and treat them as binary numbers. For example, if you have three zeros in your string, you get:
0 000 ....0..0....0...
1 001 ....0..0....o...
2 010 ....0..o....0...
3 011 ....0..o....o...
4 100 ....o..0....0...
5 101 ....o..0....o...
6 110 ....o..o....0...
7 111 ....o..o....o...
You can implement that with bitwise operators or by treating the chars that you want to replace like an odometer.
Below is an implementation in C. I'm not familiar with C# and from the other answers I see that C# already has suitable standard classes to implement what you want. (Although I'm surprised that so many peolpe propose recursion here.)
So this is more an explanation or illustration of my comment to the question than an implementation advice for your problem.
int binrep(char str[])
{
int zero[40]; // indices of zeros
int nzero = 0; // number of zeros in string
int ncombo = 1; // number of result strings
int i, j;
for (i = 0; str[i]; i++) {
if (str[i] == '0') {
zero[nzero++] = i;
ncombo <<= 1;
}
}
for (i = 0; i < ncombo; i++) {
for (j = 0; j < nzero; j++) {
str[zero[j]] = ((i >> j) & 1) ? 'o' : '0';
}
printf("%s\n", str); // should yield here
}
return ncombo;
}
Here's a solution using recursion, and your buffer array:
private static void Main(string[] args)
{
var a = Combinations("100");
var b = Combinations("10000");
}
public static IEnumerable<string> Combinations(string input)
{
var combinations = new List<string>();
combinations.Add(input);
for (int i = 0; i < input.Length; i++)
{
char[] buffer= input.ToArray();
if (buffer[i] == '0')
{
buffer[i] = 'o';
combinations.Add(new string(buffer));
combinations = combinations.Concat(Combinations(new string(buffer))).ToList();
}
}
return combinations.Distinct();
}
The method adds the raw input as the first result. After that, we replace in a loop the 0s we see as a o and call our method back with that new input, which will cover the case of multiple 0s.
Finally, we end up with a couple duplicates, so we use Distinct.
I know that the earlier answers are better. But I don't want my code to go to waste. :)
My approach for this combinatorics problem would be to take advantage of how binary numbers work. My algorithm would be as follows:
List<string> ZeroCombiner(string str)
{
// Get number of zeros.
var n = str.Count(c => c == '0');
var limit = (int)Math.Pow(2, n);
// Create strings of '0' and 'o' based on binary numbers from 0 to 2^n.
var binaryStrings = new List<string>();
for (int i = 0; i < limit; ++i )
{
binaryStrings.Add(Binary(i, n + 1));
}
// Replace each zero with respect to each binary string.
var result = new List<string>();
foreach (var binaryString in binaryStrings)
{
var zeroCounter = 0;
var combinedString = string.Empty;
for (int i = 0; i < str.Length; ++i )
{
if (str[i] == '0')
{
combinedString += binaryString[zeroCounter];
++zeroCounter;
}
else
combinedString += str[i];
}
result.Add(combinedString);
}
return result;
}
string Binary(int i, int n)
{
string result = string.Empty;
while (n != 0)
{
result = result + (i % 2 == 0 ? '0' : 'o');
i = i / 2;
--n;
}
return result;
}
I have an string array of size 10:
[0] = "1,0000000"
[1] = "479,00000"
....
[9] = "145,0".
I want to remove the trailing ",00000" of the first 9 elements with regex and linq. Please help.
Basically I would do this like that :
var yourArray = new string[10];
var yourResult = yourArray.Take(9).Select(s => s.Split(',')[0]).ToArray();
But you can replace the Select method content with a Regex call if you wish.
Use a for-loop and string methods like IndexOf and Substring:
for(int i = 0; i < Math.Min(array.Length, 9); i++)
{
int commaIndex = array[i].IndexOf(",");
if(commaIndex >= 0) array[i] = array[i].Substring(0, commaIndex);
}
You can simply try
data.forEach(x => x.replace("ABC", "'"));
I have a string representing a byte or string of bits e.g "10011111". I want convert it to a bitarray and check if a bit is set at any given position e.g at position 3.
When i try convert that string to a byte it gives me a
"Value was either too large or too small for an unsigned byte." Convert.ToByte(reader[1].ToString()). Value of reader[1].ToString() = "11111111".
Please help.
You should put the base explicitly, which is 2 in your case:
Byte result = Convert.ToByte(reader[1].ToString(), 2);
try this way
string x = "111111000";
var cd = x.ToCharArray();
and then you can work accordingly
The conversion used by Convert.ToByte is using a decimal numeric system. An easy way to convert to a binary array using Linq would be:
bool[] array = "101001010101".Select(c => c == '1').ToArray();
Or to conserve memory:
string str = "1010101001011100";
var array = new BitArray(str.Length);
for (int i = 0; i < str.Length; i++)
{
array[i] = str[i] == '1';
}
Or just use the string itself:
bool isSet = str[3] == '1';
Hi I'm developing an client application in C# and the server is written in c++
the server uses:
inline void StrToInts(int *pInts, int Num, const char *pStr)
{
int Index = 0;
while(Num)
{
char aBuf[4] = {0,0,0,0};
for(int c = 0; c < 4 && pStr[Index]; c++, Index++)
aBuf[c] = pStr[Index];
*pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128);
pInts++;
Num--;
}
// null terminate
pInts[-1] &= 0xffffff00;
}
to convert an string to int[]
in my c# client i recieve:
int[4] { -14240, -12938, -16988, -8832 }
How do I convert the array back to an string?
I don't want to use unsafe code (e.g. pointers)
Any of my tries resulted in unreadable strings.
EDIT:
Here is one of my approch:
private string IntsToString(int[] ints)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < ints.Length; i++)
{
byte[] bytes = BitConverter.GetBytes(ints[i]);
for (int j = 0; j < bytes.Length; j++)
s.Append((char)(bytes[j] & 0x7F));
}
return s.ToString();
}
I know I need to take care of endianess but as the server is running on my local machine and the server too, I assume that this is not a problem.
My other try was to use an struct with explicit layout and same FieldOffset for integer and chars but it doesn't work, either.
Maybe try something like (using LINQ):
int[] fromServer = { -14240, -12938, -16988, -8832, };
string reconstructedStr = new string(fromServer.SelectMany(BitConverter.GetBytes).Select(b => (char)(b - 128)).ToArray());
Untested, but there's something to start from. Don't know if the subtraction of 128 is correct.
You can create a comma separated string this way:
string str = String.Join(", ", intArray.Select(x => x.ToString()).ToArray());
var ints = new[] {-14240, -12938, -16988, -8832};
var result = string.Join("-", ints.Select(i => BitConverter.ToString(BitConverter.GetBytes(i))));
Console.WriteLine(result); //60-C8-FF-FF-76-CD-FF-FF-A4-BD-FF-FF-80-DD-FF-FF
BitConverter.ToString can be replaced by something else here, depending on how you will parse string later.