Split and store an integer into two byte - c#

I am working on a Embedded systems and I have only 2 Bytes of storage. I need to store a JSON response in those 2 byte. the JSON response is a string containing 2 digits. How can I convert the string to an unsigned integer split and save into those 2 bytes. I am using C#:
var results = "16";
I need to convert this and store it into 2 bytes.

As your value is only 2 digits long you just need 1 byte to store it.
You can just call Byte.Parse("16") and you will get 16 as a byte.
You can then store your byte whereever you want.

What #TheBlueOne said - a two digit number, even when hexadecimal requires just 1 byte - but for larger numbers you can use
BitConverter.GetBytes.
var s2 = "FF01";
var n = Convert.ToUInt16(s2, 16);
var bytes = BitConverter.GetBytes(n);
//bytes[0] = 1
//bytes[1] = 255

Related

How to store integers efficiently in bytes ?

I'm looking for a good and efficient way to store integers in bytes.
The situation is the following:
I have two integers, Value 1 is "1857" (11bit) and Value 2 is "14" (4bit) and 2 bytes (16bit).
What I'm looking for, is to store the 2 integers in the 2 bytes. This mean cut the first integer, put 8 bits in the first byte and the rest plus the second integer in the second byte. Also I need to get them back together.
Is there a way or .net class to do that?
I've found the BitConverter class, but thats not what I'm looking for because this class only convert one integer to an full byte array.
You could use bit operators for that: bitwise and (&), or (|), and shift left (<<) and right (>>):
int value1 = 1857;
int value2 = 14;
int result = value1 | (value2 << 11);
To get the original values back you have to reverse that:
int result1 = result & 0x7ff; // 1857
int result2 = result >> 11; // 14

Converting Hexidecimal Strings to Numeric Types and back

I need a function to convert hex values in the format 0xFFFF (2 Bytes) to decimal (unsigned and signed).
For example:
0xFFFE is 65534 (unsigned)
0xFFFE is -2 (signed)
I need also the same thing for 4 Bytes and 1 Byte.
All these options (3 * 2 options) I need to convert back - from decimal to hex (total 12 options).
My function should look like this:
string Myconverter(int ByteSize, bool IsFromHextoDecimal, bool IsSigned)
{
...
}
If there's build in functionality that performs these conversions, I'd like to a reference/link.
Use methods in the Convert class to parse the string to a number. To parse an unsigned 2 byte value you use the ToUInt16 method, and specify the base 16:
ushort value = Convert.ToUInt16("0xFFFF", 16);
Use these methods for other format:
ToInt16 = signed 2 byte
ToUInt32 = unsigned 4 byte
ToInt32 = signed 4 byte
ToByte = unsigned 1 byte
ToSByte = signed 1 byte
To format a number to a hexadecimal string you can use the X format (or x to get lower case letters) and specify the number of digits:
string formatted = value.ToString("X4");
That will however not have the 0x prefix, so if you want that you have to add it:
string formatted = "0x" + value.ToString("X4");

How to create byte[] with length 16 using FromBase64String [duplicate]

This question already has an answer here:
Calculate actual data size from Base64 encoded string length
(1 answer)
Closed 10 years ago.
I have a requirement to create a byte[] with length 16. (A byte array that has 128 bit to be used as Key in AES encryption).
Following is a valid string
"AAECAwQFBgcICQoLDA0ODw=="
What is the algorithm that determines whether a string will be 128 bit? Or is trial and error the only way to create such 128 bit strings?
CODE
static void Main(string[] args)
{
string firstString = "AAECAwQFBgcICQoLDA0ODw=="; //String Length = 24
string secondString = "ABCDEFGHIJKLMNOPQRSTUVWX"; //String Length = 24
int test = secondString.Length;
byte[] firstByteArray = Convert.FromBase64String((firstString));
byte[] secondByteArray = Convert.FromBase64String((secondString));
int firstLength = firstByteArray.Length;
int secondLength = secondByteArray.Length;
Console.WriteLine("First Length: " + firstLength.ToString());
Console.WriteLine("Second Length: " + secondLength.ToString());
Console.ReadLine();
}
Findings:
For 256 bit, we need 256/6 = 42.66 chars. That is rounded to 43 char. [To make it divisible by 4 add =]
For 512 bit, we need 512/6 = 85.33 chars. That is rounded to 86 char. [To make it divisible by 4 add ==]
For 128 bit, we need 128/6 = 21.33 chars. That is rounded to 22 char. [To make it divisible by 4 add ==]
A base64 string for 16 bytes will always be 24 characters and have == at the end, as padding.
(At least when it's decodable using the .NET method. The padding is not always inlcuded in all uses of base64 strings, but the .NET implementation requires it.)
In Base64 encoding '=' is a special symbol that is added to end of the Base64 string to indicate that there is no data for these chars in original value.
Each char is equal to 6 original bits of data, so to produce 8 bit values the string length has to be dividable by 4 without remainder. (6 bits * 4 = 8 bits * 3). When the resulting BASE64 string is shorter than 4n then '=' are added at the end to make it valid.
Update
Last char before '==' encodes only 2 bits of information, so by replacing it with all possible Base64 chars will give you only 4 different keys out of 64 possible combinations. In other words, by generating strings in format "bbbbbbbbbbbbbbbbbbbbbb==" (where 'b' is valid Base64 character) you'll get 15 duplicate keys per each unique key.
You can use PadRight() to pad the string to the end of it with a char that you will later remove once decrypted.

How to convert 2 Guids into string of max 50 characters length (2 way conversion)

have an interesting problem - I need to convert 2 (randomly) generated Guids into a string. Here are the constraints:
string max 50 charactes length.
only numbers and small letters can be used (0123456789abcdefghijklmnopqrstuvwxyz)
the algorithm has to be 2 way - need to be able to decode the encoded string into same 2 separate guids.
I've browsed a lot looking for toBase36 conversion bo so far no luck with Guid.
Any ideas? (C#)
First of all, you're in luck, 36^50 is around 2^258.5, so you can store the information in a 50 byte base-36 string. I wonder, though, why anybody would have to use base-36 for this.
You need to treat each GUID as a 128-bit number, then combine them into a 256-bit number, which you will then convert to a base-36 'number'. Converting back is doing the same in reverse.
Guid.ToByteArray will convert a GUID to a 16 byte array. Do it for both GUIDs and you have a 32 byte (which is 256 bits) array. Construct a BigInt from that array (there's a constructor), and then just convert that number to base-36.
To convert a number to base-36, do something like this (I assume everything is positive)
const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
string ConvertToBase36(BigInt number)
{
string result = "";
while(number > 0)
{
char digit = string[number % 36];
result += digit;
number /= 36;
}
}

Equivalent of sprintf in C#?

Is there something similar to sprintf() in C#?
I would for instance like to convert an integer to a 2-byte byte-array.
Something like:
int number = 17;
byte[] s = sprintf("%2c", number);
string s = string.Format("{0:00}", number)
The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).
However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2
(edit: question changed from string to byte[])
To get the bytes, use Encoding:
byte[] raw = Encoding.UTF8.GetBytes(s);
(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)
Actually, a shorter version of the first bit is:
string s = number.ToString("00");
But the string.Format version is more flexible.
EDIT: I'm assuming that you want to convert the value of an integer to a byte array and not the value converted to a string first and then to a byte array (check marc's answer for the latter.)
To convert an int to a byte array you can use:
byte[] array = BitConverter.GetBytes(17);
but that will give you an array of 4 bytes and not 2 (since an int is 32 bits.)
To get an array of 2 bytes you should use:
byte[] array = BitConverter.GetBytes((short)17);
If you just want to convert the value 17 to two characters then use:
string result = string.Format("{0:00}", 17);
But as marc pointed out the result will consume 4 bytes since each character in .NET is 2 bytes (UTF-16) (including the two bytes that hold the string length it will be 6 bytes).
It turned out, that what I really wanted was this:
short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();
The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.

Categories