It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to write a chip8 emulator in C#. It will be necessary to simulate in software the operations that take place in hardware on the real chip.
There is an opcode that requires detecting a whether a borrow occurred during the subtraction of two binary numbers.
Byte1 - Byte2
Does anyone have any ideas as to how I can use C# to tell if a borrow occurred or not?
After searching in Wikipedia for the mysterious opcode you didn't mention, and looking for some implementations. I can conclude that the opcodes 8XY5 and 8XY7 (where X and Y are register identifiers) will do substractions.
For 8XY5 the register X will be set to the value of the register X minus the value of the register Y. And the register F will be set to 1 if the value of the register Y is greater or equal to the value of the register X (0 otherwise).
For 8XY7 the register X will be set to the value of the register Y minus the value of the register X. And the register F will be set to 1 if the value of the register X is greater or equal to the value of the register Y (0 otherwise).
This is the "pseudo"-code for 8XY5:
x = opcode[1]
y = opcode[2]
if (register[x] >= register[y])
register[0xF] = 1
else
register[0xF] = 0
result = register[x] - register[y]
if result < 0
result += 256
register[x] = result
and this is the "pseudo"-code for 8XY7:
x = opcode[1]
y = opcode[2]
if (register[y] >= register[x])
register[0xF] = 1
else
register[0xF] = 0
result = register[y] - register[x]
if result < 0
result += 256
register[x] = result
And here is a C# implementation:
const byte B_0 = 0x0;
const byte B_1 = 0x1;
const byte B_F = 0xF;
static void Main()
{
byte[] registers = new byte[16];
registers[0x1] = 255;
registers[0x2] = 127;
Opcode8XY5(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Opcode8XY7(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Console.ReadLine();
}
static void Opcode8XY5(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[x] >= registers[y] ? B_1 : B_0;
registers[x] = (byte)(registers[x] - registers[y]);
}
static void Opcode8XY7(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[y] >= registers[x] ? B_1 : B_0;
registers[x] = (byte)(registers[y] - registers[x]);
}
Check this implementation for reference.
You will need to compare each bit of the bytes... If the second byte bit is set but not the first, you have a borrow condition:
static void Main(string[] args) {
byte b1 = byte.Parse(args[0]);
byte b2 = byte.Parse(args[1]);
bool borrow = false;
for (int mask = 0x01; mask <= 0x80; mask <<= 1) {
if ((b2 & mask) > (b1 & mask)) {
borrow = true;
}
}
Console.WriteLine(Convert.ToString(b1, 2).PadLeft(8, '0'));
Console.WriteLine(Convert.ToString(b2, 2).PadLeft(8, '0'));
Console.WriteLine("borrowed: {0}", borrow);
}
There may be a very clever boolean logic that gives you the answer, but I cannot come up with it now.
You need to do the math with wider type provided that the typecast was not sign-propagating. Then check if the result has the 8th bit set to 1. If it is set then borrowing had place. Then save a result as byte.
Related
This question already has answers here:
Delphi Extended to C#
(2 answers)
Closed 3 years ago.
How to correctly convert Delphi Extended type to C# decimal?
I have tried code from this post https://stackoverflow.com/a/34550718/2550543 ,with some values it works fine, but not with all.
Example :
000000000000A08C0B40 == 4500, correct
0050AA7D3A1E33D30140 == 6,59999, correct
00D0F753E3A59BC4F73F == 25769803,776, should be 0.006
00A0703D0AD7A3B0FD3F == 1481763717,12, should be 0.345
Yep, both incorrect values ends with 3F byte, if that means something ...
Can somebody help me with that? :)
Code i have used so far :
var extendedSize = 10;
var buf = new byte[extendedSize];
// Populate buffer with something like: { 0x00, 0x68, 0x66, 0x66, 0x66, 0x66, 0x66, 0xA2, 0x02, 0x40 } = 10.15
// Read(buf, extendedSize);
var sign = (buf[extendedSize - 1] & 0x80) == 0x80 ? -1 : 1;
buf[extendedSize - 1] = (byte)(buf[extendedSize - 1] & 0x7F);
var exp = BitConverter.ToUInt16(buf, extendedSize - 2);
var integral = (buf[extendedSize - 3] & 0x80) == 0x80 ? 1 : 0;
// Calculate mantissa
var mantissa = 0.0;
var value = 1.0;
var fractal = BitConverter.ToUInt64(buf, 0);
while (fractal != 0)
{
value = value / 2;
if ((fractal & 0x4000000000000000) == 0x4000000000000000) // Latest bit is sign, just skip it
{
mantissa += value;
}
fractal <<= 1;
}
return sign * (1 << (exp - 16383)) * (integral + mantissa);
return sign * (1 << (exp - 16383)) * (integral + mantissa);
Here be careful of your optimizations. Left shift works as a fast power of two if the right side argument is positive. For negative numbers this does not work as you would expect since the result of the power operation must be a floating point number for negative exponents and bit shifts will only produce an integer result. You can recover the correct answer by removing this "optimization" :
return sign * (Math.Pow(2, exp - 16383)) * (integral + mantissa);
I've also corrected the code in the linked answer from your question. Do note the caveats from that answer as well - this implementation does not correctly handle denormal numbers, NaN, INF, and other special cases. It could (should) also catch cases of extended values which are normal but fall outside the representable range of double. It would be up to you to decide whether that is important for your use case.
I have a C#/Mono app that reads data from an ADC. My read functions returns it as ulong. The data is in two complement and I need to translate it into int. E.g.:
0x7FFFFF = + 8,388,607
0x7FFFFE = + 8,388,606
0x000000 = 0
0xFFFFFF = -1
0x800001 = - 8,388,607
0x800000 = - 8,388,608
How can I do this?
const int MODULO = 1 << 24;
const int MAX_VALUE = (1 << 23) - 1;
int transform(int value) {
if (value > MAX_VALUE) {
value -= MODULO;
}
return value;
}
Explanation: MAX_VALUE is the maximum possible positive value that can be stored in 24 signed int, so if the value is less or equal then that, it should be returned as is. Otherwise value is unsigned representation of two-complement negative number. The way two-complement works is that negative number is written as a number modulo MODULO, which would effectively mean that MODULO is added. So to convert it back to signed we subtract MODULO.
currently im working on a solution for a prime-number calculator/checker. The algorythm is already working and verry efficient (0,359 seconds for the first 9012330 primes). Here is a part of the upper region where everything is declared:
const uint anz = 50000000;
uint a = 3, b = 4, c = 3, d = 13, e = 12, f = 13, g = 28, h = 32;
bool[,] prim = new bool[8, anz / 10];
uint max = 3 * (uint)(anz / (Math.Log(anz) - 1.08366));
uint[] p = new uint[max];
Now I wanted to go to the next level and use ulong's instead of uint's to cover a larger area (you can see that already), where i tapped into my problem: the bool-array.
Like everybody should know, bool's have the length of a byte what takes a lot of memory when creating the array... So I'm searching for a more resource-friendly way to do that.
My first idea was a bit-array -> not byte! <- to save the bool's, but haven't figured out how to do that by now. So if someone ever did something like this, I would appreciate any kind of tips and solutions. Thanks in advance :)
You can use BitArray collection:
http://msdn.microsoft.com/en-us/library/system.collections.bitarray(v=vs.110).aspx
MSDN Description:
Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
You can (and should) use well tested and well known libraries.
But if you're looking to learn something (as it seems to be the case) you can do it yourself.
Another reason you may want to use a custom bit array is to use the hard drive to store the array, which comes in handy when calculating primes. To do this you'd need to further split addr, for example lowest 3 bits for the mask, next 28 bits for 256MB of in-memory storage, and from there on - a file name for a buffer file.
Yet another reason for custom bit array is to compress the memory use when specifically searching for primes. After all more than half of your bits will be 'false' because the numbers corresponding to them would be even, so in fact you can both speed up your calculation AND reduce memory requirements if you don't even store the even bits. You can do that by changing the way addr is interpreted. Further more you can also exclude numbers divisible by 3 (only 2 out of every 6 numbers has a chance of being prime) thus reducing memory requirements by 60% compared to plain bit array.
Notice the use of shift and logical operators to make the code a bit more efficient.
byte mask = (byte)(1 << (int)(addr & 7)); for example can be written as
byte mask = (byte)(1 << (int)(addr % 8));
and addr >> 3 can be written as addr / 8
Testing shift/logical operators vs division shows 2.6s vs 4.8s in favor of shift/logical for 200000000 operations.
Here's the code:
void Main()
{
var barr = new BitArray(10);
barr[4] = true;
Console.WriteLine("Is it "+barr[4]);
Console.WriteLine("Is it Not "+barr[5]);
}
public class BitArray{
private readonly byte[] _buffer;
public bool this[long addr]{
get{
byte mask = (byte)(1 << (int)(addr & 7));
byte val = _buffer[(int)(addr >> 3)];
bool bit = (val & mask) == mask;
return bit;
}
set{
byte mask = (byte) ((value ? 1:0) << (int)(addr & 7));
int offs = (int)addr >> 3;
_buffer[offs] = (byte)(_buffer[offs] | mask);
}
}
public BitArray(long size){
_buffer = new byte[size/8 + 1]; // define a byte buffer sized to hold 8 bools per byte. The spare +1 is to avoid dealing with rounding.
}
}
I'm trying to debug some bit shifting operations and I need to visualize the bits as they exist before and after a Bit-Shifting operation.
I read from this answer that I may need to handle backfill from the shifting, but I'm not sure what that means.
I think that by asking this question (how do I print the bits in a int) I can figure out what the backfill is, and perhaps some other questions I have.
Here is my sample code so far.
static string GetBits(int num)
{
StringBuilder sb = new StringBuilder();
uint bits = (uint)num;
while (bits!=0)
{
bits >>= 1;
isBitSet = // somehow do an | operation on the first bit.
// I'm unsure if it's possible to handle different data types here
// or if unsafe code and a PTR is needed
if (isBitSet)
sb.Append("1");
else
sb.Append("0");
}
}
Convert.ToString(56,2).PadLeft(8,'0') returns "00111000"
This is for a byte, works for int also, just increase the numbers
To test if the last bit is set you could use:
isBitSet = ((bits & 1) == 1);
But you should do so before shifting right (not after), otherwise you's missing the first bit:
isBitSet = ((bits & 1) == 1);
bits = bits >> 1;
But a better option would be to use the static methods of the BitConverter class to get the actual bytes used to represent the number in memory into a byte array. The advantage (or disadvantage depending on your needs) of this method is that this reflects the endianness of the machine running the code.
byte[] bytes = BitConverter.GetBytes(num);
int bitPos = 0;
while(bitPos < 8 * bytes.Length)
{
int byteIndex = bitPos / 8;
int offset = bitPos % 8;
bool isSet = (bytes[byteIndex] & (1 << offset)) != 0;
// isSet = [True] if the bit at bitPos is set, false otherwise
bitPos++;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
There are many hashing methods but I want to compose bit hash with 8096 bits long. Is it possible to achieve this?
For example when I enter "House" I should get a string like:
"0101010001010101..." (8096 bits)
How can i achieve this (using C# 4.0 is ok)?
If you wonder why I need such thing, I need it for comparing Signature Files & Vector Space Model.
For fast non-cryptographic hashes you can examine the FNV family. By careful and suitable variation you should be able to construct an 8096-bit hash that is reasonably fast.
If speed is not a primary concern but simplicity and quality are then you can simply use a variant of MD5 to make a non-cryptographic hash.
Hash(x) = MD5(0 || x) || MD5(1 || x) ... MD5(62 || x) || MD5(63 || x)<32>, where "||" is the concatenation operation and only the low order 32 bits of the final hash are used, will give you an 8096 bit hash.
EDIT
Here is small code sample showing the MD5 concept:
using System;
using System.Security.Cryptography;
using System.Text;
namespace Hash8096
{
class MainClass
{
public static byte [] H8096(byte [] x) {
byte [] Result = new byte[8096 / 8];
byte [] Xplus1 = new byte[x.Length + 1];
x.CopyTo(Xplus1, 1);
int ResultOffset = 0;
int AmountLeft = Result.Length;
for (int i=0; i<64; i++) {
// do MD5(i || x)
var md5 = MD5.Create();
Xplus1[0] = (byte) i;
var hash = md5.ComputeHash(Xplus1);
int NumToCopy = Math.Min(hash.Length, AmountLeft);
Array.Copy(hash, 0, Result, ResultOffset,NumToCopy);
ResultOffset += NumToCopy;
AmountLeft -= NumToCopy;
}
return Result;
}
public static void Main (string[] args)
{
byte [] x = Encoding.UTF8.GetBytes("Hello World!");
byte [] MonsterHash = H8096(x);
Console.WriteLine ("Monster hash in hex follows:");
Console.WriteLine(BitConverter.ToString(MonsterHash));
}
}
}