将小数转换为位并检查 [英] convert decimal to bit and check

查看:55
本文介绍了将小数转换为位并检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以将我的反馈以int类型提供给我的设备

exp:146,33等...

c ++ .net是否提供任何内置函数或方法将它们转换为位数?我是使用Visual Studio 2008中的Windows窗体应用程序来实现的.

另一个问题是我如何将位数拆分为10001000到8,以便我可以检查每个位是否关闭?

i have a device which will giv me the feedback in int type

exp:146,33 etc...

is c++ .net provide any build-in function or method to convert them to bit number?i m using windows form application in visual studio 2008.

another question is how can i split a bit number lets said 10001100 to 8 pieces so i can check each bit is turn off or not?

推荐答案

我相信方法会将您的int转换为ASCII或Unicode表示形式,而不是等效的二进制形式.您可以将int强制转换为其他适当大小的类型:

字节-8位
ushort-16位
uint-32位

I believe the ToString method will convert your int to an ASCII or Unicode representation, not a binary equivalent. You could cast your int to another appropriately sized type:

byte - 8-bits
ushort - 16-bits
uint - 32-bits

result = (byte)MyInt;



查找每个位的值很简单;使用&运算符,将一个常量与您的值进行和



Finding the value of each bit is simple; use the & operator to AND your value with a constant

if (result & 0x01)
{ bool bit0 = true;}
if (result & 0x02)
{ bool bit1 = true;}
.
.
.
if (result & 0x80)
{ bool bit7 = true;}



这是一种蛮力方法,您最终会得到8个不同的值,但是在某些应用程序中可能会很方便.在执行从int到较小值的转换之前,请确保检查该值是否在该类型的正确范围内,否则会出现错误.也就是说,如果您的int值为256或更大,请不要尝试将其强制转换为byte类型.



It''s a brute force method, and you''ll end up with 8 different values, but that might be handy in some applications. Before you perform a cast from int to something smaller, be sure to check that the value is in the proper range for the type else you''ll get an error. That is, if your int value is 256 or greater, don''t try to cast it to a byte type.




您可以将整数转换为包含二进制表示形式的字符串:

Hi,

you can convert the integer to a string that holds the binary representation:

int integerValue = 25;
string *bits = Convert::ToString(integerValue,2);



然后,可以使用string.substring函数获取单个位:



Then to get the single bit you can use the string.substring function:

string *bit = bits->Substring(2, 1);



然后,您只需要检查字符串"bit"的内容.

也许有一个更简单的解决方案.

最好的问候,

JF



Then you would only need to check for the content of the string "bit".

Maybe there is a more simple solution.

Best regards,

JF


是的,C ++支持位掩码(使用与号)和位移位(使用大于或小于两倍的符号) ).谷歌这些条款(或在此处开头).
Yes, C++ supports bit masking (use the ampersand) a bit shifting (use double greater than or double less than signs). Google those terms (or start here).


这篇关于将小数转换为位并检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆