"Pad Left" with 0's on a char array - c#

G'day,
I have a char array that varies in size based on the length of some data. The array will never be larger than 24 though. It may however, be less than 24. As a result of this I need to "pad left" with 0's, as in add more elements to the left of the array to make it 24. I have below some code that does this, just wondering if there is a faster way or more efficient way to do so. Thanks!
Note: I don't think this is a duplicate as I am working with char[]'s not strings.
char[] dataLen = Convert.ToString(data.Length, 2).ToCharArray();
int j = 0;
char[] tmp = new char[24];
for (int i = 0; i < 24; i++)
{
if (i < (24 - dataLen.Length))
tmp[i] = '0';
else
tmp[i] = dataLen[j++];
}
dataLen = tmp;

Why don't you simply use String.PadLeft?
char[] data = "abcdefgh".ToCharArray(); // sample data
data = new string(data).PadLeft(24, '0').ToCharArray();
That should be efficient and is also very readable.

how about :
string z24 = "000000000000000000000";
tmp = z24.Take(24 - dataLen.Length).Union(dataLen).ToArray();

I would simply use a string for all operations, and use PadLeft to do the padding.
string input = new string(data);
string result = input.PadLeft(24, '0');
Then convert it to a char[] if you really need to:
char[] chars = result.ToCharArray();
(Also, your Convert.ToString(data.Length, 2) doesn't return their string representation, new string(data) does)

Related

Append array data into a string

I have written this piece of code:
int i = 0;
br.BaseStream.Position = i;
armorvalues[i] = br.ReadBytes(0x000E91D4);
string[] outbyte= new string[0x000E91D4];
for (int j=0; j < 0x000E91D4; j++)
{
outbyte[j] = Convert.ToString(String.Format("{0:X2}", armorvalues[0][j]));
}
Now since this is an array and I want to some algorithmic operations on the whole data, I need to convert it into a string. i need to append it in a single string. What should I do?
Not sure why you want to do so, maybe if you explain better your need then it'll be good. But for your question:
You can use string.Join:
var strValue = string.Join(" ", outbyte);
And instead of doing it after the look you can also:
var strValue = string.Join(" ", armorvalues[0].Select(item => String.Format("{0:X2}", item)));
Take a look at the StringBuilder class
StringBuilder sb = new StringBuilder(0x000E91D4*2); // length * 2 since every byte is going to be represented by 2 chars
for (int j=0; j < 0x000E91D4; j++)
{
sb.Append(Convert.ToString(String.Format("{0:X2}", armorvalues[0][j])));
}
string yourString = sb.ToString();
Edit:
I was not aware of that string.Join overload that takes an IEnumerable, that it more elegant, go with Gilad Green's solution or if you don't want the values be separated by an empty space (" ") just do
string output = string.Concat(armorvalues[0].Select(item => String.Format("{0:X2}", item)));

Check if byte stored as string of bits is set at a given position

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';

Char array wont print at indexes

I have a char array that print A-Z if i convert it to a string but when I try to get a character from an index location I get nothing? ..
char[] codes= new char[156];
for (int i = 65; i < 91; i++) codes[i] = (char)i;
Console.WriteLine(codes[2]);
Because you're starting to store the char's at index 65..
Console.WriteLine(codes[65]); // A
It has to do with the fact that you created a gigantic array but only are populating a small section of it and indexing into a portion that contains no data.
You could consider simplifying using a range..
var chars = Enumerable.Range(65, 90).Select(c => (char)c).ToArray();
Console.WriteLine(chars[2]);
Or you can modify your code to this.
char[] codes = new char[26];
for (int i = 0; i < 26; i++)
{
codes[i] = (char)i;
codes[i] += 'A';
}
Console.WriteLine(codes[2]);
You try the below code
Console.WriteLine(codes[2].ToString());
The reason is Console.WriteLine can display only the string value.

C# hex to ascii

I'm trying to convert a String of hex to ASCII, using this:
public void ConvertHex(String hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
}
String ascii = sb.ToString();
MessageBox.Show(ascii);
}
but I get an out or bounds exception, I'm sure its a glaring error but other code I have tried does not work either. What am I doing wrong?
This code will convert the hex string into ASCII, you can copy paste this into a class and use it without instancing
public static string ConvertHex(String hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = string.Empty;
hs = hexString.Substring(i,2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
Notes
2 = the no. of hexString chars used to represent an ASCII character.
System.Convert.ToUInt32(hs, 16) = "convert the base 16 hex substrings to an unsigned 32 bit int"
There are four three problems here:
Since you're incrementing i by 2 on each iteration, you need to terminate at hexString.Length - 1. This doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.
You're taking the wrong number of characters from hexString.
hs is never used.
You're not appending anything to sb.
Try this:
for (int i = 0; i < hexString.Length; i += 2)
{
string hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
Note that there's no need to qualify the types with their namespace, System (assuming you've referenced it at the top of the file with a using statement).
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
Do you notice you're never using hs ??
And that you're converting the first 2 chars over and over?
Since you are incrementing your index by 2, you need to stop your loop one-before-the-end of the length of the string. Otherwise your last iteration of the loop will try to read characters past the end of the string.
for (int i = 0; i < hexString.Length - 1, i += 2)

How get the count of an array? inC#

char[] charArray = startno.ToCharArray();
//using this arry
//i want to cheque this
int i=0;
count = 0;
while (chenum [i] != "0")
{
count++;
i++;
}
string s = "0";
string zero = "0";
for (i = 1; i <= count; i++)
{
s = s + zero;
}
will u help me to correct this code...
eg:(00001101) i need to add this no with 1.
for that i want to convert this value to int.if i convert to int the no will be(1101)+1 no will be (1102).after adding i want the answer (00001102).
how many zeros do you want?? You can use string.pad
int count = 1102;
int NumOfZeros = 10;
string s = count.ToString().PadLeft(NumOfZeros, '0');
there is also the number formatter.
count.ToString("D10");
String num = "000001101";
int item = int.Parse(num);
item++;
String output = item.ToString("D8");
You need to use String.Format("{0:00000000}", 1101);, which would be 00001101
If you are storing this number as an int (and you should) 1102 annd 00001102 are the same thing. Use string formatting later when you need to output the value with some zeros.
1102.ToString("D8") will give you the string "00001102"
Also, possible duplicates of this question: Pad with leading zeros
Try int.parseInt(startNo) instead of converting it to a char array.

Categories