int value to Hex and put it in int array - c#

i have this code
int[] i = new int[2]
i[0] = 0x13;
i[1] = 0x88;
here a value 5000 is converted to hex (1388) and put in an int array.
I want to make it so i can put in what i want with a int parameter. E.g. ``var represents decimal 6000 and it should convert it to hex (1770) and end up as
int[] i = new int[2]
i[0]= 0x17
i[1]= 0x70
in the array.

Try this
UInt16 input = 0x7017;
byte[] i = new byte[2];
i[0] = (byte)(input & 0xff);
i[1] = (byte)((input >> 8) & 0xff);​

Related

Extract a byte into a specific bit

I have one byte of data and from there I have to extract it in the following manner.
data[0] has to extract
id(5 bit)
Sequence(2 bit)
HashAppData(1 bit)
data[1] has to extract
id(6 bit)
offset(2 bit)
Required functions are below where byte array length is 2 and I have to extract to the above manner.
public static int ParseData(byte[] data)
{
// All code goes here
}
Couldn't find any suitable solution to how do I make it. Can you please extract it?
EDIT: Fragment datatype should be in Integer
Something like this?
int id = (data[0] >> 3) & 31;
int sequence = (data[0] >> 1) & 3;
int hashAppData = data[0] & 1;
int id2 = (data[1] >> 2) & 63;
int offset = data[1] & 3;
This is how I'd do it for the first byte:
byte value = 155;
byte maskForHighest5 = 128+64+32+16+8;
byte maskForNext2 = 4+2;
byte maskForLast = 1;
byte result1 = (byte)((value & maskForHighest5) >> 3); // shift right 3 bits
byte result2 = (byte)((value & maskForNext2) >> 1); // shift right 1 bit
byte result3 = (byte)(value & maskForLast);
Working demo (.NET Fiddle):
https://dotnetfiddle.net/lNZ9TR
Code for the 2nd byte will be very similar.
If you're uncomfortable with bit manipulation, use an extension method to keep the intent of ParseData clear. This extension can be adapted for other integers by replacing both uses of byte with the necessary type.
public static int GetBitValue(this byte b, int offset, int length)
{
const int ByteWidth = sizeof(byte) * 8;
// System.Diagnostics validation - Excluded in release builds
Debug.Assert(offset >= 0);
Debug.Assert(offset < ByteWidth);
Debug.Assert(length > 0);
Debug.Assert(length <= ByteWidth);
Debug.Assert(offset + length <= ByteWidth);
var shift = ByteWidth - offset - length;
var mask = (1 << length) - 1;
return (b >> shift) & mask;
}
Usage in this case:
public static int ParseData(byte[] data)
{
{ // data[0]
var id = data[0].GetBitValue(0, 5);
var sequence = data[0].GetBitValue(5, 2);
var hashAppData = data[0].GetBitValue(7, 1);
}
{ // data[1]
var id = data[1].GetBitValue(0, 6);
var offset = data[1].GetBitValue(6, 2);
}
// ... return necessary data
}

An efficient way to Base64 encode a byte array?

I have a byte[] and I'm looking for the most efficient way to base64 encode it.
The problem is that the built in .Net method Convert.FromBase64CharArray requires a char[] as an input, and converting my byte[] to a char[] just to convert it again to a base64 encoded array seems pretty stupid.
Is there any more direct way to do it?
[[EDIT:]] I'll expaling what I want to acheive better - I have a byte[] and I need to return a new base64 encoded byte[]
Byte[] -> String:
use
system.convert.tobase64string
Convert.ToBase64String(byte[] data)
String -> Byte[]:
use
system.convert.frombase64string
Convert.FromBase64String(string data)
Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[].
However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:
string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);
This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)
Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):
static public void testBase64EncodeToBuffer()
{
for (int i = 1; i < 200; ++i)
{
// prep test data
byte[] testData = new byte[i];
for (int j = 0; j < i; ++j)
testData[j] = (byte)(j ^ i);
// test
testBase64(testData);
}
}
static void testBase64(byte[] data)
{
if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
}
static public byte[] appendBase64(byte[] data
, int offset
, int size
, bool addLineBreaks = false)
{
byte[] buffer;
int bufferPos = 0;
int requiredSize = (4 * ((size + 2) / 3));
// size/76*2 for 2 line break characters
if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);
buffer = new byte[requiredSize];
UInt32 octet_a;
UInt32 octet_b;
UInt32 octet_c;
UInt32 triple;
int lineCount = 0;
int sizeMod = size - (size % 3);
// adding all data triplets
for (; offset < sizeMod;)
{
octet_a = data[offset++];
octet_b = data[offset++];
octet_c = data[offset++];
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
if (addLineBreaks)
{
if (++lineCount == 19)
{
buffer[bufferPos++] = 13;
buffer[bufferPos++] = 10;
lineCount = 0;
}
}
}
// last bytes
if (sizeMod < size)
{
octet_a = offset < size ? data[offset++] : (UInt32)0;
octet_b = offset < size ? data[offset++] : (UInt32)0;
octet_c = (UInt32)0; // last character is definitely padded
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
// add padding '='
sizeMod = size % 3;
// last character is definitely padded
buffer[bufferPos - 1] = (byte)'=';
if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
}
return buffer;
}
byte[] base64EncodedStringBytes = Encoding.ASCII.GetBytes(Convert.ToBase64String(binaryData))
Based on your edit and comments.. would this be what you're after?
byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));
You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.
To retrieve your image from byte to base64 string....
Model property:
public byte[] NomineePhoto { get; set; }
public string NomineePhoneInBase64Str
{
get {
if (NomineePhoto == null)
return "";
return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
}
}
IN view:
<img style="height:50px;width:50px" src="#item.NomineePhoneInBase64Str" />
import base64
encoded = base64.b64encode(b'[3.\x01#\xbcr\xa9/$\xc3\ xe1 "')
print(encoded)
data = base64.b64decode(encoded)
print(data)
This method is efficient irrespective of the characters. For reference I included space, Double Quotes too.
public void ProcessRequest(HttpContext context)
{
string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
MemoryStream str = new MemoryStream();
context.Response.Clear();
Byte[] bytes = (Byte[])dr[0];
string d = System.Text.Encoding.Default.GetString(bytes);
byte[] bytes2 = Convert.FromBase64String(d);
//context.Response.Write(d);
Image img = Image.FromStream(new MemoryStream(bytes2));
img.Save(context.Response.OutputStream, ImageFormat.Png);
context.Response.Flush();
str.WriteTo(context.Response.OutputStream);
str.Dispose();
str.Close();
conn.Close();
context.Response.End();
}

C# Convert Int To Two Hex Bytes?

I have an integer that I need to convert to a four digit hex value.
For example, lets say the int value is 16. What I am looking for is a way to go from 16 to
0x00 0x10.
Any suggestions would be greatly appreciated!!!
Try this:
var input = 16;
var bytes = new byte[2];
bytes[0] = (byte)(input >> 8); // 0x00
bytes[1] = (byte)input; // 0x10
var result = (bytes[0] << 8)
| bytes[1];
// result == 16
Here's one with regular expressions, just for fun:
Regex.Replace(number.ToString("X4"), "..", "0x$0 ").TrimEnd();
Alternately, a little more general solution is to do it by byte array (then you can use this for strings or other data types)
public static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-","");
}
int i = 39;
string str = "ssifm";
long l = 93823;
string hexi = ByteArrayToString(BitConverter.GetBytes(i));
string hexstr = ByteArrayToString(Encoding.Ascii.GetBytes(str));
string hexl = ByteArrayToString(BitConverter.GetBytes(l));
This returns them in a 'FF' format, you can add the '0x' yourself by adding this after the ToString() instead:
return "0x"+hex.Replace("-", " 0x");
Shift it! Mask it! Mask it! string.Format it!
int n = 16;
string.Format("0x{0:x2} 0x{1:x2}", (n & 0xff00) >> 8, n & 0xff); // 0x00 0x10
Here's a demo.
The x2 format specifier means a 2-digit hexadecimal value.
Okay, apparently you just want two bytes. Hexadecimal is not relevant here.
byte lowByte = (byte)(n & 0xff);
byte highByte = (byte)(n >> 8 & 0xff);

Convert int to byte as HEX in C#

I need to send a Hex string over the serial to a device, I do that now like this:
byte[] c = new byte[3];
c[0] = 0x57;
c[1] = 0x30;
ComPort.Write(c,0,c.Length );
Now I need to convert a value of int like 30 to c[1] = 0x30 or a int value of 34 gives c[1] = 0x34.
I hope you see what I mean.
So how can I mange this?
This format is called binary-coded decimal. For two-digit numbers, integer-divide by ten and multiply by sixteen, then add back the remainder of the division by ten:
int num = 45;
int bcdNum = 16*(num/10)+(num%10);
Another way to do this could be
c[1] = Convert.ToByte(num.ToString(), 16);
suppose int Data=2821; was to send over COM Port:
c[0]= Convert.ToByte(data & 0x00FF);
c[0]= Convert.ToByte(data & 0xFF00) >> 8);
ComPort.Write(c,0,c.Length );
int num = 1366;
string bcdNum = num.ToString("X");
if (bcdNum.Length < 2)
bcdNum = "0" + bcdNum;
byte[] bytes_str=Enumerable.Range(0, bcdNum.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(bcdNum.Substring(x, 2), 16)).ToArray();

Represent a Guid as a set of integers

If I want to represent a guid as a set of integers how would I handle the conversion? I'm thinking along the lines of getting the byte array representation of the guid and breaking it up into the fewest possible 32 bit integers that can be converted back into the original guid. Code examples preferred...
Also, what will the length of the resulting integer array be?
As a GUID is just 16 bytes, you can convert it to four integers:
Guid id = Guid.NewGuid();
byte[] bytes = id.ToByteArray();
int[] ints = new int[4];
for (int i = 0; i < 4; i++) {
ints[i] = BitConverter.ToInt32(bytes, i * 4);
}
Converting back is just getting the integers as byte arrays and put together:
byte[] bytes = new byte[16];
for (int i = 0; i < 4; i++) {
Array.Copy(BitConverter.GetBytes(ints[i]), 0, bytes, i * 4, 4);
}
Guid id = new Guid(bytes);
System.Guid guid = System.Guid.NewGuid();
byte[] guidArray = guid.ToByteArray();
// condition
System.Diagnostics.Debug.Assert(guidArray.Length % sizeof(int) == 0);
int[] intArray = new int[guidArray.Length / sizeof(int)];
System.Buffer.BlockCopy(guidArray, 0, intArray, 0, guidArray.Length);
byte[] guidOutArray = new byte[guidArray.Length];
System.Buffer.BlockCopy(intArray, 0, guidOutArray, 0, guidOutArray.Length);
System.Guid guidOut = new System.Guid(guidOutArray);
// check
System.Diagnostics.Debug.Assert(guidOut == guid);
Somehow I had much more fun doing it this way:
byte[] bytes = guid.ToByteArray();
int[] ints = new int[bytes.Length / sizeof(int)];
for (int i = 0; i < bytes.Length; i++) {
ints[i / sizeof(int)] = ints[i / sizeof(int)] | (bytes[i] << 8 * ((sizeof(int) - 1) - (i % sizeof(int))));
}
and converting back:
byte[] bytesAgain = new byte[ints.Length * sizeof(int)];
for (int i = 0; i < bytes.Length; i++) {
bytesAgain[i] = (byte)((ints[i / sizeof(int)] & (byte.MaxValue << 8 * ((sizeof(int) - 1) - (i % sizeof(int))))) >> 8 * ((sizeof(int) - 1) - (i % sizeof(int))));
}
Guid guid2 = new Guid(bytesAgain);
Will the build-in Guid structure not suffice?
Constructor:
public Guid(
byte[] b
)
And
public byte[] ToByteArray()
Which, returns a 16-element byte array that contains the value of this instance.
Packing the bytes into integers and visa versa should be trivial.
A Guid is typically just a 128-bit number.
-- Edit
So in C#, you can get the 16 bytes via
byte[] b = Guid.NewGuid().ToByteArray();

Categories

Resources