logo
down
shadow

C++ Simple Converting from Binary to Decimal


C++ Simple Converting from Binary to Decimal

By : user2956635
Date : November 22 2020, 10:56 AM
I hope this helps you . In you can copy structs, unions etc but can not copy arrays directly. Becuase of this reason, you can not return an array and assign it to another array.
Instead of somearr[8] you can use std::array or std::vector. These stl containers can be copied and thus will solve your problem.
code :


Share : facebook icon twitter icon
Converting decimal to binary and then binary to unknown format?

Converting decimal to binary and then binary to unknown format?


By : Grodahn
Date : March 29 2020, 07:55 AM
I hope this helps . First of all, 645 in base 2 is 1010000101. (Your code gives an incorrect result for some reason).
Once you realize that, I think it's fairly simple to see that the "unknown format" can be reached by simply breaking the binary value into chunks of 8 bits (adding 0's at the beginning where necessary) to give your intermediate binary format, and then converting each chunk (byte) into decimal (base 10).
iProblems with substr, integers and loops in converting decimal to binary and binary to decimal

iProblems with substr, integers and loops in converting decimal to binary and binary to decimal


By : user2970766
Date : March 29 2020, 07:55 AM
To fix this issue Finally, I've managed to edit my code :)
to Konstantinos Chalkias I found out what I had to do :D
code :
package decimalBinary;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DecBin {
    public static void main(String[] args) throws NumberFormatException, IOException {
        int conargs1,conargs2;
        // conargs1 is input
        // conargs2 is mode, if = 1 then dec2bin, if = 2 then bin2dec
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number: ");
        conargs1=Integer.parseInt(br.readLine());
        System.out.println("Enter mode: ");
        conargs2 = Integer.parseInt(br.readLine());
        System.out.println(conargs2==1 ? "Dec2Bin" : (conargs2==2 ? "Bin2Dec" : "none"));
        if (args.length == 2){ // TO BINARY
            if(conargs2==1){
                System.out.println(DecBin.dec2bin(String.valueOf(conargs1)));
            }else if (conargs2==2){ // TO DECIMAL
                System.out.println(DecBin.bin2dec(String.valueOf(conargs1)));
            }
            System.exit(0);
        }
    }

    public static String dec2bin(String arg){
        String out = null;
        String tmp;
        long i, x;
        int maxpower = 30;
        x = Integer.parseInt(arg);

        if (x == 0){
            return "0";
        }else if (x > 0){ // positive decimals
            if (x > Math.pow(2, maxpower)) {
                return "should be no larger than " + String.valueOf(2 ^ maxpower);
            }
            out = "";

            int binary[] = new int[30];
            int index = 0;
            while(x > 0){
                binary[index++] = (int) (x % 2);
                x = x/2;
            }

            for(i = index-1;i >= 0;i--){
                out = out+binary[(int) i];
            }
        }else{ // negative decimals
            // x = -x;
            x = Math.abs(x); // convert positive of decimal to binary 
            if (x > Math.pow(2, maxpower)) {
                return "should be no larger than " + String.valueOf(2 ^ maxpower);
            }
            long xBinaryPositive;
            xBinaryPositive = Long.parseLong(DecBin.dec2bin(String.valueOf(x)));
            String xBinaryInverted;
            out = "";


            xBinaryInverted = String.valueOf(xBinaryPositive).replace('0', '2').replace('1', '0').replace('2', '1');
            long xBinaryInvertedIntVal;
            xBinaryInvertedIntVal = DecBin.bin2dec(xBinaryInverted);
            out = DecBin.dec2bin(String.valueOf(xBinaryInvertedIntVal+1));
        }
        return out;
    }

    public static long bin2dec(String binaryInput){
        long binary = Long.parseLong(binaryInput);
        long decimal = 0;
        long power = 0;
        while(true){
            if(binary == 0){
                break; 
            } else {
                long tmp = binary % 10;
                decimal += tmp * Math.pow(2, power);
                binary = binary/10;
                power++;
            }
        } 
        return decimal; 
    }
}
Arduino Converting Decimal to Binary to Decimal

Arduino Converting Decimal to Binary to Decimal


By : user6801869
Date : March 29 2020, 07:55 AM
seems to work fine Since you are going through an array 0-7 of 1s, you should be using bit shifting:
code :
int convertBinToDec(boolean Bin[]) {
  int ReturnInt = 0;
  for (int i = 0; i < 8; i++) {
    if (Bin[7 - i]) {
      Serial.print("Set Bit ");
      Serial.print(i);
      ReturnInt += 1<<i;
      Serial.print(" ==> ");
      Serial.print(1<<i);
      Serial.print(", ");
    }
  }
  return ReturnInt;
}

DecToBin: 1 -> 00000001 -> Set Bit 0 ==> 1, 1
DecToBin: 2 -> 00000010 -> Set Bit 1 ==> 1, 2
DecToBin: 3 -> 00000011 -> Set Bit 0 ==> 1, Set Bit 1 ==> 1, 3
DecToBin: 4 -> 00000100 -> Set Bit 2 ==> 2, 4
DecToBin: 5 -> 00000101 -> Set Bit 0 ==> 1, Set Bit 2 ==> 2, 5
DecToBin: 6 -> 00000110 -> Set Bit 1 ==> 1, Set Bit 2 ==> 2, 6
DecToBin: 7 -> 00000111 -> Set Bit 0 ==> 1, Set Bit 1 ==> 1, Set Bit 2 ==> 2, 7
DecToBin: 8 -> 00001000 -> Set Bit 3 ==> 4, 8
converting the binary to decimal when binary is stored in an array

converting the binary to decimal when binary is stored in an array


By : Amirkhan Madyarbek
Date : March 29 2020, 07:55 AM
wish of those help this is the code I have written but it gives incorrect answers and I can't figure out why , For arbitrary sized byte[] you can use BigInteger.
code :
public void test(String[] args) {
    byte[] b = new byte[] {1,2,3,4,5};
    BigInteger bi = new BigInteger(b);
    System.out.println(bi.toString(10));
}
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu

Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu


By : Raju
Date : March 29 2020, 07:55 AM
may help you . Well, there you go :P Decided to use a switch object because it was interesting. However i'm finding it tough to exit the switch with input '5'
code :
class switch(object):
    value = None
    def __new__(class_, value):
        class_.value = value
        return True

def case(*args):
    return any((arg == switch.value for arg in args))

def bintodec(binnum):
    return int(str(binnum), 2)

def add(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(first) + int(second))
    print('')

def sub(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass    
    print('result')
    print(int(second) - int(first))
    print('')


def show_menu():

    while True:
        print ("What do you want to do?")
        print ("1. Enter the first number")
        print ("2. Enter the second number")
        print ("3. Add the two numbers together")
        print ("4. Subtract the second number from the first")
        print ("5. Exit the program\n")            
        ask_for_input = input('Enter Switch\n')
        ask_for_input = int(ask_for_input)

        while switch(ask_for_input):
            if case(1):
                ask_for_1_num = input("Enter the first number\n")
                break
            if case(2):
                ask_for_2_num = input("Enter the second number\n")
                break
            if case(3):
                add(ask_for_1_num, ask_for_2_num)
                break
            if case(4):
                sub(ask_for_1_num, ask_for_2_num)
                break
            if case(5):
                break
            break    

def main():
    show_menu()

if __name__ == '__main__':
    main()        
Related Posts Related Posts :
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Make a C++ class look like a numpy array using swig
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • ld: -bind_at_load and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together
  • C++ storing #define as std::string would give size as zero compile time
  • How to use static linking with OpenSSL in C/C++
  • What is the difference between a trap, an error, a failure and program abortion?
  • Dynamic members allocation in qt
  • How to reduce object file size when compiling for VxWorks 5.5.1?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org