@@ -328,6 +328,22 @@ var rechner = (function (rechner) {
328
328
return parseInt ( binary , 2 ) ;
329
329
}
330
330
331
+ // logic binary to decimal - Signed -> Two's complement
332
+
333
+ function getSignedInteger ( binary ) {
334
+ let negative = ( bits [ 0 ] === '1' ) ;
335
+ if ( negative ) {
336
+ let inverse = '' ;
337
+ for ( let i = 0 ; i < bits . length ; i ++ ) {
338
+ inverse += ( bits [ i ] === '0' ? '1' : '0' ) ;
339
+ }
340
+ return ( parseInt ( inverse , 2 ) + 1 ) * - 1 ;
341
+ } else {
342
+ return parseInt ( bits , 2 ) ;
343
+ }
344
+ }
345
+
346
+
331
347
// logic decimal to binary
332
348
333
349
// IIFE to scope internal variables
@@ -403,6 +419,26 @@ var rechner = (function (rechner) {
403
419
return - Math . abs ( num ) ;
404
420
}
405
421
422
+ // logic decimal to binary- Signed -> Two's complement
423
+
424
+ function toTwosComplement ( integer , numberBytes , dontCheckRange ) {
425
+ // @integer - > the integer to convert
426
+ // @numberBytes -> the number of bytes representing the number (defaults to 1 if not specified)
427
+
428
+ var numberBits = ( numberBytes || 1 ) * 8 ;
429
+
430
+ // make sure its in range given the number of bits
431
+ if ( ! dontCheckRange && ( integer < ( - ( 1 << ( numberBits - 1 ) ) ) || integer > ( ( 1 << ( numberBits - 1 ) ) - 1 ) ) )
432
+ throw "Integer out of range given " + numberBytes + " byte(s) to represent." ;
433
+
434
+ // if positive, return the positive value
435
+ if ( integer >= 0 )
436
+ return integer ;
437
+
438
+ // if negative, convert to twos complement representation
439
+ return ~ ( ( ( - integer ) - 1 ) | ~ ( ( 1 << numberBits ) - 1 ) ) ;
440
+ }
441
+
406
442
// functions Buttons
407
443
408
444
// AC - All Clear
0 commit comments