I have negative binary number which has a sign bit and want to write a program to get its gray code. However, I can only find the solution for positive number. So here I am asking this question. Thanks.
how to convert a negative binary number to its gray code
2k views Asked by Albert Zhou At
2
There are 2 answers
0
Alexey Polonsky
On
It is possible to convert a signed integer to Gray code if the target bit width is known:
int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_encode_signed(int n, int width_bits) {
int all_ones = (1 << width_bits) - 1;
return (n >= 0 ? gray_encode(n) : gray_encode(abs(n)) + all_ones);
}
For example, this is 4 bits Gray code for values from -7 to 7:
decimal 4bit gray code
-7 1011
-6 1100
-5 1110
-4 1101
-3 1001
-2 1010
-1 1000
0 0000
1 0001
2 0011
3 0010
4 0110
5 0111
6 0101
7 0100
Related Questions in BINARY
- ELF binary has inconsistency detected by ld.so: dl-call-libc-early-init.c: 37: Assertion `sym != NULL' failed
- How to only estimate neonatal mortality using syncmrates in Stata?
- change binary data like "111 into 001" in python by using if else or using regex
- Error in eval(predvars, data, env) : object 'Juice_practice' not found when running binary logistic regression in r
- How to subtract large binary numbers?
- How to convert n most significant bits in a hexadecimal byte string in Python 3
- Is it possible to represent -3/32 as a binary floating-point value using only 7 bits
- how to copy binary files to the worker nodes on Databricks?
- Decimal to Binary program not working on my local machine but works perfectly on online compiler
- After saving to txt file all of the data is corrupted
- Reading .bson file with Rust
- Why won't my binary search work for numbers that are double digits?
- MIPS Aiken to Binary
- Minimizing the number of basic arithmetic/binary operators needed to arrive at all others
- Resnet50 for binary classification predicts all the images to be of the same class
Related Questions in CONVERTERS
- ABAP convert Database char to lowercase
- What is the difference between converting PNG images to JPEG using convertio.co
- Culture info usage while converting string to float type
- Convert Docx To Markdown With Specific Tables
- Convert single column txt file to multi column csv
- convert hatanaka to rinex for multiple files
- How to convert this text contrast function to version for hsl values
- convert PDF to HTML(one paragraph in each <span>tag)
- Glulxe/gblorb game or file editing
- WGET -HTTP request sent, awaiting response... 404 Not Found
- How to perform a binding inside the calling of a converter in WPF XAML?
- Any simple and lightweight tool to transform LaTex to MathML?
- Attempting to build a publication reference converter - cannot get it to function correctly
- How to convert the magnitudes cointained in a nc file and then cut the data according to the data in a shp file with R
- Issue: Custom converters are not triggered during CSV file writing with CsvHelper
Related Questions in BIT-MANIPULATION
- How to flip bits in one operation with c#?
- Fast BCD addition
- Choosing a sequence of bitwise operations
- receives an incomprehensible value and it is not clear how it gets it
- Wrong result for left bit shift in JS
- Find a bit with no duplicates among multiple bits in Java
- how to convert different length of bits into byte array?
- Convert Variable Width Bitstream (2-bit or 4-bit symbols) into Fixed Width
- Minimizing the number of basic arithmetic/binary operators needed to arrive at all others
- LC-3 Assembly OR operation
- Why are same conditions getting different results?
- Why does bit shifting with a large amount work in C?
- Need help to solve DSA : Find position of set bit in java
- Does this simple code not containing any loop generate a loop in assembly?
- Lua 5.1 bitwise operations using arithmetic for 64bit numbers
Related Questions in GRAY-CODE
- I want to convert Gray code to binary in python and c
- How to obtain this result from a 256 bits monochrome picture?
- How to program a MIP solver to find balanced Gray code for mixed radices?
- how convert opencv c++ graycode->decode() function to cv2 python
- Stereo camera structured light disparity problem
- What is the intuition behind gray code generation?
- what is a GR image?
- How to print n-bit gray codes specifically using backtracking?
- How to generate a sequence of indexes of a nested loop that has cache locality?
- Optimal bit twiddling for the One's complement absolute value operation on modern x86 processors
- Opencv Decode Gray code pattern tutorial 3D scanner Problems
- k-combination of n items with "Gray code"-like property
- Python GrayCode saved as string directly to decimal
- Hi am confused about output when we give input as 4 while it works for 3
- clock domain crossing of a mutli bit signal
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Gray code can only be calculated for non-negative numbers, using the following method:
The same method won't work for negative numbers because of Two's complement representation of binary numbers.