如何输出在C变量的二进制值++ [英] How to output the Binary value of a variable in C++
问题描述
我有一个家庭作业在我的C ++编程类编写输出变量的值的二进制值的函数。
I've got a homework assignment in my C++ programming class to write a function that outputs the binary value of a variable's value.
因此,举例来说,如果我的a的值设置为一个char我应该得到A输出的二进制值。
So for example, if I set a value of "a" to a char I should get the binary value of "a" output.
我的C ++的教授是不是在整个世界上最伟大,我无法让我的code。使用,他给了我们神秘的例子来工作。现在,我的code只是输出的11111111二进制值,不管我把它太(除非它的NULL然后我得到00000000)。
My C++ professor isn't the greatest in the whole world and I'm having trouble getting my code to work using the cryptic examples he gave us. Right now, my code just outputs a binary value of 11111111 no matter what I set it too (unless its NULL then I get 00000000).
下面是我的code:
#include <iostream>
#define useavalue 1
using namespace std;
void GiveMeTehBinary(char bin);
int main(){
#ifdef useavalue
char b = 'a';
#else
char b = '\0';
#endif
GiveMeTehBinary(b);
system("pause");
return 0;
}
void GiveMeTehBinary(char bin){
long s;
for (int i = 0; i < 8; i++){
s = bin >> i;
cout << s%2;
}
cout << endl << endl;
}
由于一吨提前家伙。你总是非常有帮助:)
Thanks a ton in advance guys. You're always extremely helpful :)
编辑:现在固定 - 多谢:D问题是,我并没有存储从位移位的值。我已经更新了code以上的工作状态。
Fixed now - thanks a bunch :D The problem was that I was not storing the value from the bit shift. I've updated the code to its working state above.
推荐答案
编译器应该提醒你一下贵code某些语句没有影响 1 。考虑
The compiler should warn you about certain statements in your code that have no effect1. Consider
bin >> i;
这什么也不做,因为你不存储此操作的结果的任何地方。
This does nothing, since you don’t store the result of this operation anywhere.
另外,你为什么要申报 tehbinary
作为一个数组?您曾经使用所有的的有一个的元素(当前的)。这将是足够存储只是当前位
Also, why did you declare tehbinary
as an array? All you ever use is one element (the current one). It would be enough to store just the current bit.
其他的一些事情包括:
-
NULL
只能用指针值被使用。您使用的作品,但它不是预期的使用情况。你真正想要的是一个空字符,即'\\ 0'
。 - 请使用真实的,描述性的名称。我清楚地记得自己使用
tehdataz
变量称为等等,但是这确实使得code难以阅读,一旦最初的搞笑消退它都为你当你尝试很烦人读你的code,以及谁是你的分级code。 - 正确格式化code有助于理解了很多:使压痕逻辑性和一致性
NULL
must only be used with pointer values. Your usage works but it’s not the intended usage. What you really want is a null character, i.e.'\0'
.- Please use real, descriptive names. I vividly remember myself using variables called
tehdataz
etc. but this really makes the code hard to read and once the initial funny wears off it’s annoying both for you when you try to read your code, and for whoever is grading your code. - Formatting the code properly helps understanding a lot: make the indentation logical and consistent.
1 如果您使用 G ++
,始终传递编译器标志 -Wall -Wextra
来获得有用的诊断你的code。
1 If you’re using g++
, always pass the compiler flags -Wall -Wextra
to get useful diagnostics about your code.
这篇关于如何输出在C变量的二进制值++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!