are there any other methods of storing binary numbers - binary

A binary number is normally stored with a fixed position MSB and a LSB; from LSB to MSB the weighting is doubled each bit. Are there any other ways of storing a binary number?
the traditional way may be the most efficient way, when requiring the lowest number of logical electronic bits needed to represent a number, but there are some disadvantages with this method. One disadvantage is that when sequentially counting the toggling of the LSB is quite high because it toggles state on each incremental count.
I was trying to scramble the weighting of each bit so that when sequentially counting, each bit that represents the binary number has the same amount of toggling. There are many advantages for achieving this method, even though more bits are required for the number.
One advantage is that the life of EEPROM would be extended because an equal amount of toggling occurs in all of the physical cells that represent the stored number. Another advantages when overclocking a cpu, error correction, and more.
If a oscilloscope probe examines a traditional address bus, the LSB has a lot of HARD work, and the MSB is very idle.
traditional method:
(number)
0000
0001
0010
0011
0100
new proposed method:
(scramble encoder)(number)

How about a binary number system like this? When counting with a very high bus speed, the transistors do not overheat and therefore limit clock speed.
The solution uses both base-2 and base-1 binary to make a number.
((base-2 binary number)*size_of_in_bits(base-1 binary number)) + base-1 binary number
so for a 16 bit bus, with the high byte binary base-2, and the low byte binary base-1, the maximum count would be
((2^8)-1)*8)+8) = 2048
The solution to the EEPROM life problem could be:
Using a EEPROM that only changes the required cells when writing new data to maximise life.
4 bytes (32bit) for the base-2 part of the number, and 13 bytes (100 bit) for the base-1 part of the number.
((32 bit base-2 binary number) x 100) + (100 bit binary base-1 tally counter)
The maximum count would be (((2^32)-1) *100)+100) = 429,496,729,700
This method should get the maximum life from the EEPROM or FLASH memory, for FLASH memory the base-1 number should be stored inverted, because the erased state is logic 1.
The EEPROM can, read, increment, write, a number 2 orders of magnitude bigger, achieving a count of 1 million instead of ten thousand.
Send me a email and I can give you the program, it works in MVS 2013 console.
lion#palmbeach.freeserve.co.uk
/* a www.goatelectronics.com solution */
/* This program is designed to test eeprom life, writing to the same page and cells */
/* 32 bit base-2 binary number + 100 bit base-1 binary number make the number*/
/* byte 0 - Most significant byte , binary base-2 number */
/* byte 1 - */
/* byte 2 - */
/* byte 3 - Least significant byte, binary base-2 number */
/* byte 4 - 8 bit CRC suffix for 32bit number, to be done later */
/* byte 5 - count 0 to 8 of binary base-1 number */
/* byte 6 - count 9 to 16 of binary base-1 number*/
/* byte 7 - count 17 to 24 of ... */
/* byte 8 - count 25 to 32 */
/* byte 9 - count 33 to 40 */
/* byte 10 - count 41 to 48 */
/* byte 11 - count 49 to 56 */
/* byte 12 - count 57 to 64 */
/* byte 13 - count 65 to 72 */
/* byte 14 - count 73 to 80 */
/* byte 15 - count 81 to 88 */
/* byte 16 - count 89 to 96 */
/* byte 17 - count 97 to 100 */
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
/* emulate the eeprom *here* , byte read and write */
unsigned char eeprom[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned int EEPROM_read (void)
{
unsigned char i_u8;
unsigned int value_u32, value_A_u32, value_B_u32, value_C_u32, value_D_u32 = 0;
unsigned int base_1_u32 = 0;
value_A_u32 = eeprom[0];
value_A_u32 = value_A_u32 << 24;
value_B_u32 = eeprom[1];
value_B_u32 = value_B_u32 << 16;
value_C_u32 = eeprom[2];
value_C_u32 = value_C_u32 << 8;
value_D_u32 = eeprom[3];
value_u32 = value_A_u32 | value_B_u32 | value_C_u32 | value_D_u32;
/* eeprom[4] reserved location for CRC checksum! */
value_u32 = value_u32 * 100;
for (i_u8 = 5; eeprom[i_u8] == 0xFF; i_u8++)
{
base_1_u32 = base_1_u32 + 8;
}
switch (eeprom[i_u8])
{
case 0x80: base_1_u32 = base_1_u32 + 1;
break;
case 0xC0: base_1_u32 = base_1_u32 + 2;
break;
case 0xE0: base_1_u32 = base_1_u32 + 3;
break;
case 0xF0: base_1_u32 = base_1_u32 + 4;
break;
case 0xF8: base_1_u32 = base_1_u32 + 5;
break;
case 0xFC: base_1_u32 = base_1_u32 + 6;
break;
case 0xFE: base_1_u32 = base_1_u32 + 7;
break;
default:; /*if here, faulty EEPROM with base-1 number*/
}
value_u32 = value_u32 + base_1_u32;
return (value_u32);
}
void EEPROM_write(unsigned int number_u32)
{
unsigned char i_u8, remainder_u8;
unsigned int value_u32;
value_u32 = number_u32;
value_u32 = value_u32 / 100;
eeprom[0] = (unsigned char)((value_u32 & 0xFF000000) >> 24);
eeprom[1] = (unsigned char)((value_u32 & 0x00FF0000) >> 16);
eeprom[2] = (unsigned char)((value_u32 & 0x0000FF00) >> 8);
eeprom[3] = (unsigned char)((value_u32 & 0x000000FF));
remainder_u8 = (unsigned char)(number_u32 % 100);
if (!remainder_u8)
{
for (i_u8 = 5; i_u8 < 18; i_u8++)
{
eeprom[i_u8] = 0x00;
}
}
for (i_u8 = 5; remainder_u8 >=8; i_u8++)
{
eeprom[i_u8] = 0xFF;
remainder_u8 = remainder_u8 - 8;
}
switch (remainder_u8)
{
case 1: eeprom[i_u8] = 0x80;
break;
case 2: eeprom[i_u8] = 0xC0;
break;
case 3: eeprom[i_u8] = 0xE0;
break;
case 4: eeprom[i_u8] = 0xF0;
break;
case 5: eeprom[i_u8] = 0xF8;
break;
case 6: eeprom[i_u8] = 0xFC;
break;
case 7: eeprom[i_u8] = 0xFE;
break;
default:; /**/
}
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned char i_u8;
unsigned int test_number_u32;
unsigned int loop_u32 = 0;
while (loop_u32 <0xFFFFFFFF)
{
test_number_u32 = EEPROM_read();
test_number_u32++;
EEPROM_write(test_number_u32);
for (i_u8 = 0; i_u8 < 18; i_u8++)
{
printf(" %x", eeprom[i_u8]);
}
printf(" \n");
loop_u32++;
}

Related

MIPS how do you do a word to binary?

I have a 1010(base 2) 4 bit bit vector and a 1010(base 10) word. I need to show that they are equal.
Not totally sure of what you are trying to do, is this what you are looking for?
// 1010(base10) = 0000 0011 1111 0010(base2) -> requires 16 bits
unsigned base2 = 10; // 1010 in base 2
unsigned base10 = 1010; // Assume only 1's and 0's are used
unsigned answer = 0;
int bit = 0;
for (int bit = 0; base10 > 0; bit++)
{
if (base10 % 10) answer |= (0x01 << bit);
base10 /= 10;
}
// At this point answer = 1010(base2)

Optimizing code for reading some VLVs in a file?

I'm trying to read some variable-length-values from a file I created.
The file contains the following:
81 7F 81 01 2F F3 FF
There are two VLVs there, 81 7F and 81 01 which are 255 and 129 in decimal.
I also created some file-reader functions that go like this:
void read_byte_from_file_to(std::fstream& file, uint8_t& to) {
file.read((char*)&to, 1);
}
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long result = 0;
static unsigned long sum = 0, depth = 0, count = 0;
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
++count;
if (c & 0x80) {
readVLV(t_midi_file);
}
sum += (c & 0x7F) << (7 * depth++);
if (count == depth) {
result = sum;
sum = 0;
depth = 0;
count = 0;
}
return result;
};
While running readVLV n times gives correct answers for the first n VLVs when reading from a file, I absolutely hate how I wrote it, which so much statics parameters and that ugly parameter reset. SO if someone could head me in the right direction I'd be very pleased.
A basic _readVLV which takes the positional state of the function could be done by writing
unsigned long _readVLV(
std::fstream& t_midi_file,
unsigned long sum,
unsigned long depth) {
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
if (c & 0x80) {
sum += _readVLV(t_midi_file, sum, depth);
++depth;
}
return (c & 0x7F) << (7 * depth);
}
and creating a global readVLV function that takes the positional information and the file like so
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long sum = 0, depth = 0, count = 0;
return _readVLV(t_midi_file, sum, depth, count);
}

Game: nine heads and tails. I am having trouble with binary stuff

You may not understand what I wrote clearly because English is not my first language.
Anyway, here is what I wrote.
public class Exercises7point11 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] binaryNumber = {{0,0,0},{0,0,0},{0,0,0}};
System.out.print("Enter a number between 0 and 511: ");
int decimalNumber = input.nextInt();
int subtractNumber = 256, number = decimalNumber;
for (int row = 0 ; row < 3; row++){
for (int column = 0 ; column < 3; column++) {
if(number >= subtractNumber) {
binaryNumber[row][column] = 1;
number = number - subtractNumber;
}
else {
subtractNumber = subtractNumber / 2;
binaryNumber[row][column] = 0;
}
}
}
// print
for (int row = 0; row < binaryNumber.length; row++){
for (int column = 0; column < binaryNumber[row].length; column++){
if (binaryNumber[row][column] == 1)
System.out.print("T ");
else if (binaryNumber[row][column] == 0)
System.out.print("H ");
if (column == 2)
System.out.print("\n");
}
}
}
Here is the details. Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (heads) and 1 (tails).
Such as,
1 0 0
0 1 0
1 1 0.
There are a total of 512 possibilities, so I can use decimal numbers 0, 1, 2, 3,..., 511 to represent all states of the matrix. Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
My problem is "subtractNumber = subtractNumber / 2; binaryNumber[row][column] = 0;" in the 18 and 19 lines. Even though 'number is greater than or equal to subtractNumber, 18 and 19 lines are read.
I don't know how I can fix it.
Thank you so much!!
The output is a 3x3 matrix, but that doesn't mean you need to use a 2d array.
Here's a simpler approach. We're turning the user's input into a binary string using the toBinaryString method, then translating the binary string into H/T.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
int input = sc.nextInt();
// Turn input to binary string
String binary = Integer.toBinaryString(input);
// Add enough zeros in front so that the string has 9 characters
binary = binary.format("%09d", Integer.parseInt(binary));
// Iterate through binary string one char at a time
for (int i = 1; i < 10; i++) {
if ('0' == binary.charAt(i - 1)) {
System.out.print("H ");
} else {
System.out.print("T ");
}
// New line after 3 letters
if (i % 3 == 0) {
System.out.println();
}
}
}
Example output
12 in binary is 000001100
Enter a number between 0 and 511: 12
H H H
H H T
T H H

Binary divisibility by 10

How to check if a binary number can be divided by 10 (decimal), without converting it to other system.
For example, we have a number:
1010 1011 0100 0001 0000 0100
How we can check that this number is divisible by 10?
First split the number into odd and even bits (I'm calling "even" the
bits corresponding to even powers of 2):
100100110010110000000101101110
0 1 0 1 0 0 1 0 0 0 1 1 0 1 0 even 1 0 0 1 0 1 1 0 0 0 0 0 1 1 1 odd
Now in each of these, add and subtract the digits alternately, as in
the standard test for divisibility by 11 in decimal (starting with
addition at the right):
100100110010110000000101101110 +0-1+0-1+0-0+1-0+0-0+1-1+0-1+0 =
-2 +1-0+0-1+0-1+1-0+0-0+0-0+1-1+1 = 1
Now double the sum of the odd digits and add it to the sum of the even
digits:
2*1 + -2 = 0
If the result is divisible by 5, as in this case, the number itself is
divisible by 5.
Since this number is also divisible by 2 (the rightmost digit being
0), it is divisible by 10.
Link
If you are talking about computational methods, you can do a divisiblity-by-5 test and a divisibility-by-2 test.
The numbers below assume unsigned 32-bit arithmetic, but can easily be extended to larger numbers.
I'll provide some code first, followed by a more textual explanation:
unsigned int div5exact(unsigned int n)
{
// returns n/5 as long as n actually divides 5
// (because 'n * (INV5 * 5)' == 'n * 1' mod 2^32
#define INV5 0xcccccccd
return n * INV5;
}
unsigned int divides5(unsigned int n)
{
unsigned int q = div5exact(n);
if (q <= 0x33333333) /* q*5 < 2^32? */
{
/* q*5 doesn't overflow, so n == q*5 */
return 1;
}
else
{
/* q*5 overflows, so n != q*5 */
return 0;
}
}
int divides2(unsigned int n)
{
/* easy divisibility by 2 test */
return (n & 1) == 0;
}
int divides10(unsigned int n)
{
return divides2(n) && divides5(n);
}
/* fast one-liner: */
#define DIVIDES10(n) ( ((n) & 1) == 0 && ((n) * 0xcccccccd) <= 0x33333333 )
Divisibility by 2 is easy: (n&1) == 0 means that n is even.
Divisibility by 5 involves multiplying by the inverse of 5, which is 0xcccccccd (because 0xcccccccd * 5 == 0x400000001, which is just 0x1 if you truncate to 32 bits).
When you multiply n*5 by the inverse of 5, you get n * 5*(inverse of 5), which in 32-bit math simplifies to n*1 .
Now let's say n and q are 32-bit numbers, and q = n*(inverse of 5) mod 232.
Because n is no greater than 0xffffffff, we know that n/5 is no greater than (232-1)/5 (which is 0x33333333). Therefore, we know if q is less than or equal to (232-1)/5, then we know n divides exactly by 5, because q * 5 doesn't get truncated in 32 bits, and is therefore equal to n, so n divides q and 5.
If q is greater than (232-1)/5, then we know it doesn't divide 5, because there is a one-one mapping between the 32-bit numbers divisible by 5 and the numbers between 0 and (232-1)/5, and so any number out of this range doesn't map to a number that's divisible by 5.
Here is the code in python to check the divisibilty by 10 using bitwise technique
#taking input in string which is a binary number eg: 1010,1110
s = input()
#taking initial value of x as o
x = 0
for i in s:
if i == '1':
x = (x*2 + 1) % 10
else:
x = x*2 % 10
#if x is turn to be 0 then it is divisible by 10
if x:
print("Not divisible by 10")
else:
print("Divisible by 10")

Given an integer, how do I find the next largest power of two using bit-twiddling?

If I have a integer number n, how can I find the next number k > n such that k = 2^i, with some i element of N by bitwise shifting or logic.
Example: If I have n = 123, how can I find k = 128, which is a power of two, and not 124 which is only divisible by two. This should be simple, but it eludes me.
For 32-bit integers, this is a simple and straightforward route:
unsigned int n;
n--;
n |= n >> 1; // Divide by 2^k for consecutive doublings of k up to 32,
n |= n >> 2; // and then or the results.
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++; // The result is a number of 1 bits equal to the number
// of bits in the original number, plus 1. That's the
// next highest power of 2.
Here's a more concrete example. Let's take the number 221, which is 11011101 in binary:
n--; // 1101 1101 --> 1101 1100
n |= n >> 1; // 1101 1100 | 0110 1110 = 1111 1110
n |= n >> 2; // 1111 1110 | 0011 1111 = 1111 1111
n |= n >> 4; // ...
n |= n >> 8;
n |= n >> 16; // 1111 1111 | 1111 1111 = 1111 1111
n++; // 1111 1111 --> 1 0000 0000
There's one bit in the ninth position, which represents 2^8, or 256, which is indeed the next largest power of 2. Each of the shifts overlaps all of the existing 1 bits in the number with some of the previously untouched zeroes, eventually producing a number of 1 bits equal to the number of bits in the original number. Adding one to that value produces a new power of 2.
Another example; we'll use 131, which is 10000011 in binary:
n--; // 1000 0011 --> 1000 0010
n |= n >> 1; // 1000 0010 | 0100 0001 = 1100 0011
n |= n >> 2; // 1100 0011 | 0011 0000 = 1111 0011
n |= n >> 4; // 1111 0011 | 0000 1111 = 1111 1111
n |= n >> 8; // ... (At this point all bits are 1, so further bitwise-or
n |= n >> 16; // operations produce no effect.)
n++; // 1111 1111 --> 1 0000 0000
And indeed, 256 is the next highest power of 2 from 131.
If the number of bits used to represent the integer is itself a power of 2, you can continue to extend this technique efficiently and indefinitely (for example, add a n >> 32 line for 64-bit integers).
There is actually a assembly solution for this (since the 80386 instruction set).
You can use the BSR (Bit Scan Reverse) instruction to scan for the most significant bit in your integer.
bsr scans the bits, starting at the
most significant bit, in the
doubleword operand or the second word.
If the bits are all zero, ZF is
cleared. Otherwise, ZF is set and the
bit index of the first set bit found,
while scanning in the reverse
direction, is loaded into the
destination register
(Extracted from: http://dlc.sun.com/pdf/802-1948/802-1948.pdf)
And than inc the result with 1.
so:
bsr ecx, eax //eax = number
jz #zero
mov eax, 2 // result set the second bit (instead of a inc ecx)
shl eax, ecx // and move it ecx times to the left
ret // result is in eax
#zero:
xor eax, eax
ret
In newer CPU's you can use the much faster lzcnt instruction (aka rep bsr). lzcnt does its job in a single cycle.
A more mathematical way, without loops:
public static int ByLogs(int n)
{
double y = Math.Floor(Math.Log(n, 2));
return (int)Math.Pow(2, y + 1);
}
Here's a logic answer:
function getK(int n)
{
int k = 1;
while (k < n)
k *= 2;
return k;
}
Here's John Feminella's answer implemented as a loop so it can handle Python's long integers:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n+1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift <<= 1
return n + 1
It also returns faster if n is already a power of 2.
For Python >2.7, this is simpler and faster for most N:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
return 2**(n-1).bit_length()
This answer is based on constexpr to prevent any computing at runtime when the function parameter is passed as const
Greater than / Greater than or equal to
The following snippets are for the next number k > n such that k = 2^i
(n=123 => k=128, n=128 => k=256) as specified by OP.
If you want the smallest power of 2 greater than OR equal to n then just replace __builtin_clzll(n) by __builtin_clzll(n-1) in the following snippets.
C++11 using GCC or Clang (64 bits)
#include <cstdint> // uint64_t
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * 8 - __builtin_clzll(n));
}
Enhancement using CHAR_BIT as proposed by martinec
#include <cstdint>
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * CHAR_BIT - __builtin_clzll(n));
}
C++17 using GCC or Clang (from 8 to 128 bits)
#include <cstdint>
template <typename T>
constexpr T nextPowerOfTwo64 (T n)
{
T clz = 0;
if constexpr (sizeof(T) <= 32)
clz = __builtin_clzl(n); // unsigned long
else if (sizeof(T) <= 64)
clz = __builtin_clzll(n); // unsigned long long
else { // See https://stackoverflow.com/a/40528716
uint64_t hi = n >> 64;
uint64_t lo = (hi == 0) ? n : -1ULL;
clz = _lzcnt_u64(hi) + _lzcnt_u64(lo);
}
return T{1} << (CHAR_BIT * sizeof(T) - clz);
}
Other compilers
If you use a compiler other than GCC or Clang, please visit the Wikipedia page listing the Count Leading Zeroes bitwise functions:
Visual C++ 2005 => Replace __builtin_clzl() by _BitScanForward()
Visual C++ 2008 => Replace __builtin_clzl() by __lzcnt()
icc => Replace __builtin_clzl() by _bit_scan_forward
GHC (Haskell) => Replace __builtin_clzl() by countLeadingZeros()
Contribution welcome
Please propose improvements within the comments. Also propose alternative for the compiler you use, or your programming language...
See also similar answers
nulleight's answer
ydroneaud's answer
Here's a wild one that has no loops, but uses an intermediate float.
// compute k = nextpowerof2(n)
if (n > 1)
{
float f = (float) n;
unsigned int const t = 1U << ((*(unsigned int *)&f >> 23) - 0x7f);
k = t << (t < n);
}
else k = 1;
This, and many other bit-twiddling hacks, including the on submitted by John Feminella, can be found here.
assume x is not negative.
int pot = Integer.highestOneBit(x);
if (pot != x) {
pot *= 2;
}
If you use GCC, MinGW or Clang:
template <typename T>
T nextPow2(T in)
{
return (in & (T)(in - 1)) ? (1U << (sizeof(T) * 8 - __builtin_clz(in))) : in;
}
If you use Microsoft Visual C++, use function _BitScanForward() to replace __builtin_clz().
function Pow2Thing(int n)
{
x = 1;
while (n>0)
{
n/=2;
x*=2;
}
return x;
}
Bit-twiddling, you say?
long int pow_2_ceil(long int t) {
if (t == 0) return 1;
if (t != (t & -t)) {
do {
t -= t & -t;
} while (t != (t & -t));
t <<= 1;
}
return t;
}
Each loop strips the least-significant 1-bit directly. N.B. This only works where signed numbers are encoded in two's complement.
What about something like this:
int pot = 1;
for (int i = 0; i < 31; i++, pot <<= 1)
if (pot >= x)
break;
You just need to find the most significant bit and shift it left once. Here's a Python implementation. I think x86 has an instruction to get the MSB, but here I'm implementing it all in straight Python. Once you have the MSB it's easy.
>>> def msb(n):
... result = -1
... index = 0
... while n:
... bit = 1 << index
... if bit & n:
... result = index
... n &= ~bit
... index += 1
... return result
...
>>> def next_pow(n):
... return 1 << (msb(n) + 1)
...
>>> next_pow(1)
2
>>> next_pow(2)
4
>>> next_pow(3)
4
>>> next_pow(4)
8
>>> next_pow(123)
128
>>> next_pow(222)
256
>>>
Forget this! It uses loop !
unsigned int nextPowerOf2 ( unsigned int u)
{
unsigned int v = 0x80000000; // supposed 32-bit unsigned int
if (u < v) {
while (v > u) v = v >> 1;
}
return (v << 1); // return 0 if number is too big
}
private static int nextHighestPower(int number){
if((number & number-1)==0){
return number;
}
else{
int count=0;
while(number!=0){
number=number>>1;
count++;
}
return 1<<count;
}
}
// n is the number
int min = (n&-n);
int nextPowerOfTwo = n+min;
#define nextPowerOf2(x, n) (x + (n-1)) & ~(n-1)
or even
#define nextPowerOf2(x, n) x + (x & (n-1))