« en: 18 de Julio 2016, 20:58 »
Ejercicio:
We are given an integer number N (read from the console), a bit value v (read from the console as well) (v = 0 or 1) and a position P (read from the console). Write a sequence of operators (a few lines of C# code) that modifies N to hold the value v at the position P from the binary representation of N while preserving all other bits in N. Print the resulting number on the console.
El código:
using System;
class Program {
static void Main() {
long num;
Console.Write("Introduzca un número entero positivo: ");
num = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("El número en representación binaria es: "+Convert.ToString(num, 2));
Console.Write("Qué posición quieres cambiar?: ");
byte posicion;
posicion = Convert.ToByte(Console.ReadLine());
byte valor;
Console.Write("Qué valor quieres ponerle (1 ó 0)?: ");
valor = Convert.ToByte(Console.ReadLine());
if(valor == 0) {
long mask = ~(1 << posicion);
Console.WriteLine(Convert.ToString(mask, 2));
num = num & mask;
}else{
long mask = 1 << posicion;
Console.WriteLine(Convert.ToString(mask, 2));
num = num | mask;
}
Console.WriteLine("El nuevo número (representado en binario) es: "+Convert.ToString(num, 2)+" y representado en decimal es: "+num);
}
}
Saludos.
« Última modificación: 20 de Julio 2016, 12:55 por César Krall »

En línea