Converted hex formats - hex

I have a hex value that is in the format:
0x00000000:0x00000000:0x00000000:0x00000000
I need to convert it to a format like:
00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
I was hoping to be able to strip the 0x's and insert colons every two characters but that does not seem to be correct. How can I convert these two formats?

You can do this entirely with strings. In C#:
string original = "0x00000000:0x00000000:0x00000000:0x00000000";
//remove the unwanted characters
string[] split = { "0x", ":" };
split = original.Split(split, StringSplitOptions.RemoveEmptyEntries);
//format the rest in 2-char chunks
string result = "";
for (int i = 0; i < split.Length; i++)
{
for (int j = 0; j < split[i].Length; j += 2)
{
result += split[i].Substring(j, 2) + ":";
}
}
//remove the trailing ':'
result = result.Substring(0, result.Length - 1);
Error handling omitted for clarity.
Is this helpful?

Related

Last line of a datatable asp.net

I have a problem when I'm trying to a loop in a DataTable that a dataset contains.
I'm doing a loop like this:
for(int i = 0; i<ds.Tables[0].Rows.Count - 1 ; i++)
The problem is that I can't get the value of the last line with this one, but if I try to get rid of the "-1" and do a loop on the whole table, I'll have an out of range exception.
This out of range exception is because I have to check if the value of a line "i" is equal to the value of a line "i+1", like this:
if (ds.Tables[0].Rows[i]["Release_No"] != ds.Tables[0].Rows[i + 1]["Release_No"])
So if I do it in a loop, when the index is on the last line it will check if the last line is equal to i+1, and it's out of the table.
So I was trying to check if the index is on the last line, then just get the value of the last line, but it seems like it doesn't work.
if(ds.Tables[0].Rows.IndexOf(ds.Tables[0].Rows[i]) == ds.Tables[0].Rows.Count)
If anyone has an idea, let me know, and of course if it is not clear enough let me know, I'll give more information and more code.
Thanks for your help and your time!
Check if it's the last record, first.
I like to refactor code to read as close to sentence form as possible, explaining what you want it to do using named variables and methods, and that often gets me unlocked.
Try to make each line of code do one thing, and one thing only, like check if it is the last row:
var data = ds.Tables[0].Rows;
var lastRow = data.Count - 1;
for(int i = 0; i < lastRow ; i++)
{
if (i == lastRow){
// This is the last row. Handle the last row here.
}
else
{
// Handle all other rows here
var currentRecord = data[i];
var nextRecord = data[i + 1];
if (currentRecord["Release_No"] != nextRecord["Release_No"])
{
// Handle unique Releases...
}
}
}
Use less than or equal to like this
for(int i = 0; i<=ds.Tables[0].Rows.Count - 1 ; i++)
I hope this may get what you want.
Something like this is better ?
var lastRow = data.Count - 1;
var data = ds.Tables[0].Rows;
for(int i = 0; i< lastRow; i++)
{
testFirstCum = Convert.ToInt32(ds.Tables[0].Rows[i]["EDI_Accum_Quantity"]);
if ( i == lastRow)
{
if (DBNull.Value.Equals(data[i]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
else
{
var col = ds.Tables[0].Columns;
var currentRecord = data[i];
var nextRecord = data[i + 1];
if(currentRecord["Release_No"] != nextRecord["Release_No"])
{
for (int j = col[2].Ordinal; j < col.Count; j++)
{
if (DBNull.Value.Equals(data[i][j]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i][j]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
}
}
}

cryptoJS AES encrypt returning a wrong decryption [duplicate]

How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}

NPOI: Excel column formatted to decimal with SXSSFWorkbook?

I am developing a website with ASP.net (VS2015 C #).
I need to export a MySql table with a large amount of data (500000+ rows and 100 columns) to excel (xlsx), with format.
After trying many options, the NPOI (v 3.20) library allows this export using types that use streaming (SXSSFWorkbook & SXSSFSheet).
If I use XSSFWorkbook I get and Out of memory filling the rows.
With SXSSFWorkbook I have been able to format the xlsx with different fonts and colors, but I am having problems with the types of data exported:
Date types ok
Int types ok
Text ok
Decimals inputs like 100.35 --> problems, I get a text column. I need a ouput like a number 100,35.
The code I use to format the data is:
SXSSFWorkbook wb = new SXSSFWorkbook();
SXSSFSheet sh = (SXSSFSheet)wb.CreateSheet("Sheet 1");
sh.SetRandomAccessWindowSize(100);
ICellStyle testStyleHeader = wb.CreateCellStyle();
ICellStyle testStyleRow = wb.CreateCellStyle();
// Header Style
testStyleHeader.FillForegroundColor = NPOI.SS.UserModel.IndexedColors.RoyalBlue.Index;
testStyleHeader.FillPattern = FillPattern.SolidForeground;
// Double style (with 2 decimals like 453.65)
ICellStyle cellStyleDouble = wb.CreateCellStyle();
cellStyleDouble.DataFormat = wb.CreateDataFormat().GetFormat("0.00");
// Font
XSSFFont hFontBlack = (XSSFFont)wb.CreateFont();
hFontBlack.FontHeightInPoints = 11;
hFontBlack.FontName = "Calibri";
hFontBlack.Color = NPOI.SS.UserModel.IndexedColors.Black.Index;
testStyleHeader.SetFont(hFontBlack);
IRow row = sh.CreateRow(0);
int j = 0;
ICell cell = row.CreateCell(j);
// Fill Header row
cell.SetCellValue("XXXX"); cell.CellStyle = testeStyleHeader; j++; cell = row.CreateCell(j);
cell.SetCellValue("YYYY"); cell.CellStyle = testeStyleHeader; j++; cell = row.CreateCell(j);
cell.SetCellValue("ZZZZ"); cell.CellStyle = testeStyleHeader; j++; cell = row.CreateCell(j);
cell.SetCellValue("WWWW"); cell.CellStyle = testeStyleHeader; j++; cell = row.CreateCell(j);
// Fill Rows
int i = 1; // row Number
IRow row2; // No Header Row
ICell cell2; // No Header cell
while (dr.Read()) // dr is the DataReader
{
row2 = sh.CreateRow(i);
for (int cont = 0; cont < NumColumns; cont++)
{
if (cont == 0) // This column is a date
{
…. // code for date format
}
else if (cont == 3) // Double column with 2 decimals¡! (values samples 100.45 5654.80 etc.)
{
ICell cell3 = row2.CreateCell(j, NPOI.SS.UserModel.CellType.Numeric);
cell3.CellStyle = cellStyleDouble;
cell3.SetCellValue(Convert.ToDouble(dr[cont]));
}
else
{…. // code for tex format, int format etc.
}
}
i++;
}
With this code, in the decimal column (cont ==3), I get a text column.
However, with the same code, if I declare the no streaming types:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (SSFSheet)wb.CreateSheet("Sheet 1");
Only with this changes I get a perfect numeric columnn 3...
For this line:
cellStyleDouble.DataFormat = wb.CreateDataFormat().GetFormat("0.00");
I have tried with different types:
"#.#"
"#,##0.000"
"##.#"
Etc…
In some cases I get a number, but not with the desired format.
So...streaming types do not allow this formatting?
Just change the Culture Info to en-US
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-Us");
ISheet worksheet = Workbook.CreateSheet(dt.TableName);
IRow HeaderRow = worksheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell HeaderCell = HeaderRow.CreateCell(i);
HeaderCell.SetCellValue(dt.Columns[i].ColumnName);
}
for (int j = 0; j < dt.Rows.Count; j++)
{
IRow Row = worksheet.CreateRow(j + 1);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell Cell = Row.CreateCell(i);
if (dt.Columns[i].DataType.IsOfType(typeof(decimal)) && dt.Rows[j][i] != DBNull.Value)
{
Cell.SetCellType(CellType.Numeric);
Cell.SetCellValue((double)dt.Rows[j][i]);
}
else
Cell.SetCellValue(dt.Rows[j][i].ToString());
}
}
Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-Br");
It works for me!
can you try your formatting based on below code snippet. I am using this approach to format phone number.
XSSFCellStyle currencyCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat currencyDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
currrencyCellStyle.SetDataFormat(currencyDataFormat.GetFormat("00000.00")); //Formats: #####.##, 00000##.##
sometimes its tricky to find exact formatting in NPOI :). Please try below approaches
ICellStyle CellStyle = workbook.CreateCellStyle();
CellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("number"); // or Number
or
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("#.#")); // or #####.## or number

How to split QString and keep the separator in Qt?

I have a QString: "{x, c | 0x01}", and I want to split it to 7 tokens as below:
{
x
,
c
|
0x01
}
What's the best way to do it in Qt?
I tried to use QString::split(QRegExp("[\\{\\},|]")), but it DOES NOT keep the separator in the result.
Maybe this solution can serve you task:
int main(void) {
QString str { "{x, c | 0x01}" };
QRegExp separators { "[\\{\\},|]" };
QStringList list;
str.replace( " ", "" );
int mem = 0;
for(int i = 0; i<str.size(); ++i) {
if(i == str.indexOf(separators, i)) {
if(mem) list.append(str.mid(mem, i-mem)); // append str before separator
list.append(str.mid(i, 1)); // append separator
mem = i+1;
}
}
qDebug() << list;
return 0;
}
Outputs: ("{", "x", ",", "c", "|", "0x01", "}")
You can eliminate if(mem) but then use list.pop_front(); orlist.removeAll(""); after the for cycle, as first element will be a rubbish "".
Basically, you iterate through the string, check if a deliminator is found, and add the deliminator to the list. If no deliminator is found, a new 'word' is added to the list, and until the next deliminator is found, characters will be added to the word. Take a look:
//input string
QString str = "{x, c | 0x01}";
QList<QString> out;
//flag used to keep track of whether we're adding a mullti-char word, or just a deliminator
bool insideWord = false;
//remove whitespaces
str = str.simplified();
str = str.replace(" ", "");
//iterate through string, check for delims, populate out list
for (int i = 0; i < str.length(); i++)
{
QChar c = str.at(i); //get char at current index
if (c == '{' || c == '}' || c == ',' || c == '|')
{
//append deliminator
out.append(c);
insideWord = false;
}
else
{
//append new word to qlist...
if (!insideWord)
{
out.append(c);
insideWord = true;
}
//but if word already started
else
{
//add 'c' to the word in last index of the qlist
out.last().append(c);
}
}
}
//output as requested by OP
qDebug() << "String is" << out;
This can be done in a single regular expression, but has to use look-ahead and look-behind.
The expression specified in the question ([\\{\\},|]) will match a 1-character long string consisting of any of the characters {, }, , or |. QString.split will then remove that 1-character long string.
What is needed is to find the zero-character string immediately before each of those separators, using a look-ahead: (?=[\\{\\},|]) and also to find the zero-character string immediately after the separator (?<=[\\{\\},|]).
Combining these gives:
QString::split(QRegularExpression("(?=[\\{\\},|])|(?<=[\\{\\},|])"))
Which will give the desired output: ("{", "x", ",", "c", "|", "0x01", "}")

Avoiding comma separator for the last value

I am generating an output on a webpage in a format like this
({"1":"Jeff","2":"Tom","3":"Michael",})
For this, basically this is the code I am using
Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?
My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)
Assuming k is an array of strings
List<string> tokens = k.ToList<string>();
Response.Write("({" + String.join<string>(",", tokens) + "})");
Simplified and VB.Net, but i think you will get it:
Dim values As New List(Of String)(New String() {"1:Jeff", "2:Tom", "3:Michael"})
Dim result As String = "({" & String.Join(",", values.ToArray) & "})"
If k is a Collection like Array,List etc.
Depending on the number of iterations and how often this happens use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (Int32 i = 0; i < k.Length; i++)
{
sb.Append(",");
sb.Append(Convert.ToString(k.GetValue(i)));
}
if (sb.Length > 0) {
sb.Remove(0,1);
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
Another way is: However, it has to check every iteration.
StringBuilder sb = new StringBuilder();
for (Int32 i = 0; i < k.Length; i++)
{
if (sb.Length > 0) {
sb.Append(",");
}
sb.Append(Convert.ToString(k.GetValue(i)));
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
you can decrease your loop instead increase... like
for (Int32 i = k.Length; i > 0; i--)
and put: if (i == 1) removeComa;
Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
Response.Write(Convert.ToString(k.GetValue(i)) + (i == k.Length - 1 ? "" : ","));
}
//
Response.Write("}" + ")");
One of my favorite fixes for this is to use a prepend instead and only set comma as the seperator value after the first item (sorry for the VB):
Dim seperator As String = ""
For i As Integer = 0 To k.Length
Response.Write(seperator + Convert.ToString(k.GetValue(i)))
seperator = ","
Next
In your loop, simply use insert a "break" when the count reaches the last digit and that has been processed?
If you change how you output to write the first object in the collection then everyone after preceded by a comma it should work fine.
Response.Write("(" + "{");
//
Response.Write(Convert.ToString(k.GetValue(0)));
for (Int32 i = 1; i < k.Length; i++)
{
Response.Write("," + Convert.ToString(k.GetValue(i)));
}
//
Response.Write("}" + ")");
An alternative would be writing to a stringbuilder and outputting all but the last character

Resources