I'm packing some binary data as a short, but want to have 4x values of 0-F.. And would like to do this without having a bunch of switch() cases reading the string.split of a hex
Someone have a clever, elegant solution for this or should I just long-hand it?
eg; 1C4A = (1, 12, 4, 10)
Shift in and out
var a = 1;
var b = 12;
var c = 4;
var d = 10;
// in
var packed = (short) ((a << 12) | (b << 8) | (c << 4) | d);
// out
a = (packed >> 12) & 0xf;
b = (packed >> 8) & 0xf;
c = (packed >> 4) & 0xf;
d = packed & 0xF;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Output
1
12
4
10
You can shift by 4 (or divide and multiply by 16) to move numbers into different place values. Then mask and shift your packed number to get your original numbers back.
Eg if you want to store 1 and 2 you could do:
int packed = (1 << 4) + 2;
int v1 = (packed & 0xF0) >> 4;
int v2 = packed & 0x0F;
Console.WriteLine($"{v1}, {v2}");
>>> 1, 2
I read 3 bytes in a binary file which I need to convert into an integer.
I use this code to read the bytes :
LastNum last1Hz = new LastNum();
last1Hz.Freq = 1;
Byte[] LastNumBytes1Hz = new Byte[3];
Array.Copy(lap_info, (8 + (32 * k)), LastNumBytes1Hz, 0, 3);
last1Hz.NumData = LastNumBytes1Hz[2] << 16 + LastNumBytes1Hz[1] << 8 + LastNumBytes1Hz[0];
last1Hz.NumData is an integer.
This seems to be the good way to convert bytes into integers in the posts i have seen.
Here is a capture of the values read:
But the integer last1Hz.NumData is always 0.
I'm missing something but can't figure out what.
You need to use brackets (because addition has a higher priority than bit shifting):
int a = 0x87;
int b = 0x00;
int c = 0x00;
int x = c << 16 + b << 8 + a; // result 0
int z = (c << 16) + (b << 8) + a; // result 135
Your code should look like this:
last1Hz.NumData = (LastNumBytes1Hz[2] << 16) + (LastNumBytes1Hz[1] << 8) + LastNumBytes1Hz[0];
I think the problem is an order of precedence issue. + is evaluated before <<
Put brackets in to force the bit shift to be evaluated first.
last1Hz.NumData = (LastNumBytes1Hz[2] << 16) + (LastNumBytes1Hz[1] << 8) + LastNumBytes1Hz[0];
How does C# execute this?
static void Main(string[] args)
{
int i = 4;
i *= 4 + 8 / 2;
Console.WriteLine(i);
}
This was asked in one of the interview Questions. And I applied BODMAS to it.
But it was wrong. Please Explain.
It will be executed equivalent to the following code:
int i = 4;
int temp = 8 / 2;
temp = 4 + temp;
i = i * temp;
The compiler will shorten it down because it can calculate the constant that is on the right of i *=, so in reality it will compile to this:
int i = 4;
i *= 8;
i *= 4 + 8 / 2 is executed as:
i = i * (4 + (8 / 2))
That's the correct way of reading it.
Operator precedence is very clear on this: The / is a multiplicative operator and is applied first, then the +. The *= is an assignment operator and is applied last.
So:
8 / 2 = 4
4 + 4 = 8
i *= 8;
so i will be 4 * 8 = 32;
I am trying to create a small software that does the Affine Cipher, which means that K1 and the amount of letters in the alphabet (using m for this number) must be coprime, that is gcd(k1, m) == 1.
Basically it's like this:
I have a plaintext: hey
I have K1: 7
I have K2: 5
Plaintext in numerical format is:
8 5 25
8 - from h (the position in the alphabet) and **
5 25** goes the same for e and y
Encrypted: 7 13 18
Which is the formula:
k1 * 8 + k2 mod 27 = 7
k1 * 5 + k2 mod 27 = 13
k1 * 25 + k2 mod 27 = 18
I have a function that crypts this but I don't know how to decrypt.
For example I have 7 for h. I want to get the number 8 back again, knowing 7, k1 and k2.
Do you guys have any ideas ?
Some function where you input k1, k2, result (7 for example, for h), and it gives me back 8, but I really don't know how to reverse this.
The function for encryption is this:
public List<int> get_crypted_char(string[] strr)
{
List<int> l = new List<int>();
int i;
for (i = 0; i < strr.Length; i++)
{
int ch = int.Parse(strr[i]);
int numberback = k1 * ch + 5;
numberback = (numberback % 27);
l.Add(numberback);
}
return l;
}
Where: string[] strr is a string that contains the plaintext.
Function example:
get_crypted_char({"e","c","b"})
The result would be a list like this {"5","3","2"}
UPDATE:
Here is a link from wikipedia about this encryption, and also decryption, but ... I don't really understand "how to"
http://en.wikipedia.org/wiki/Affine_cipher
It is not possible (in general case, for affine cipher, see update below). That's why module operation is so frequently used in security algorithms - it is not reversible. But, why don't we try?
result = (k1 * input + k2) % 27 (*1)
Let's take the first letter:
result = (7 * 8 + 5) % 27 = 7
That's cool. Now, because we said, that:
result = (k1 * input + k2) % 27
the following is also true:
k1 * input + k2 = 27 * div + result (*2)
where
div = (k1 * input + k2) / 27 (integral division)
It is quite obvious (if a % b = c, then a = b*n + c, where n is the result of integer division a/b).
You know the values of k1 (which is 7), k2 (5) and result (7). So, when we put these values to (*2), we get the following:
7 * input + 5 = 27 * div + 7 //You need to solve this
As you can see, it is impossible to solve this, because you would need to know also the result of the integral division - translating this to your function's language, you would need the value of
numberback / 27
which is unknown. So answer is: you cannot reverse your function's results, using only output it returns.
** UPDATE **
I focused too much on the question's title, so the answer above is not fully correct. I decided not to remove it, however, but write an update.
So, the answer for your particular case (affine cipher) is: YES, you can reverse it.
As you can see on the wiki, decryption function for affine cipher for the following encrytption function:
E(input) = a*input + b mod m
is defined as:
D(enc) = a^-1 * (enc - b) mod m
The only possible problem here can be computation of a^-1, which is modular multiplicative inverse.
Read about it on wiki, I will provide only example.
In your case a = k1 = 7 and m = 27. So:
7^-1 = p mod 27
7p = 1 mod 27
In other words, you need to find p, which satisfies the following: 7p % 27 = 1.
p can be computed using extended euclidean algorithm and I computed it to be 4 (4 * 7 = 28, 28 % 27 = 1).
Check, if can decipher your output now:
E(8) = 7*8 + 5 mod 27 = 7
D(7) = 4 * (7 - 5) mod 27 = 8
Hope that helps :)
Please note that the other answers do not take into account the the algorithm at hand is the Affine Cipher, ie there are some conditions at hand, the most important one the coprime status of k1 and m.
In your case it would be:
m = 27; // letters in your alphabet
k1 = 7; // coprime with m
k2 = 5; // no reqs here, just that a value above 27 is the same as mod 27 of that value
int Encrypt(int letter) {
return ((letter * k1) + k2) % m;
}
int Decrypt(int letter) {
return ((letter - k2) * modInverse(k1, m)) % m;
}
Tuple<int, Tuple<int, int>> extendedEuclid(int a, int b)
{
int x = 1, y = 0;
int xLast = 0, yLast = 1;
int q, r, m, n;
while (a != 0)
{
q = b / a;
r = b % a;
m = xLast - q * x;
n = yLast - q * y;
xLast = x; yLast = y;
x = m; y = n;
b = a; a = r;
}
return new Tuple<int, Tuple<int, int>>(b, new Tuple<int, int>(xLast, yLast));
}
int modInverse(int a, int m)
{
return (extendedEuclid(a, m).Item2.Item1 + m) % m;
}
ModInverse implementation taken from http://comeoncodeon.wordpress.com/2011/10/09/modular-multiplicative-inverse/.
I have created a program that will tell the modular inverse of something. I will let you use it. It is posted below.
# Cryptomath Module
def gcf(a, b):
# Return the GCD of a & b using Euclid's Algorithm
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
# Return the modular inverse of a % m, which is
# the number x such that a*x % m = 1
if gcf(a, m) != 1:
return None # No mode inverese if a & m aren't relatively prime
# Calculate using the Extended Euclidean Algorithm:
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3 # // is the integer division operator
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q *
v3), v1, v2, v3
return u1 % m
Note: The modular inverse is found using the extended euclidean algorithm. Here is the Wikipedia entry for it: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
Note: This needs to be imported as a module to be used. Hope it helps.
assume I have decimal X
I want to calculate 3 byte as a,b,c where a.bc Gig is near X.
I want it to be clean and as short as it possible.
I've already implement it but it is very bad but works.
for example X = 2972117368, I want a = 2, b = 7, c = 6 . how?
2972117368/(1024*1024*1024) = 2.76799999922514
X will be always lesser than 9.99 gigabyte.
Is seems like you're most of the way there:
decimal x = 2972117368;
double gig = Convert.ToDouble(x) / 1073741824.0;
byte a = (byte)Math.Floor(gig); // works for up to 127 gig - actually up to 256
byte b = (byte)(Math.Floor(gig * 10) % 10);
byte c = (byte)(Math.Floor(gig * 100) % 10);
Edited: For some typos & logical errors
Encoding.ASCII.GetBytes((double.Parse((X / (1024.0 * 1024 * 1024)).ToString("0.00")) * 100).ToString())